【发布时间】:2015-01-17 22:56:58
【问题描述】:
我正在尝试通过 WCF 服务进行文件上传/下载。传输协议是 HTTP。我已将绑定设置为用户Streaming 作为传输模式,并且已经尝试了几天以使其正常工作,但没有成功。我设法让它适用于小文件。上传大文件时,在服务器上创建文件,写入若干字节,然后事务失败。
服务托管在 Windows Azure WebRole 环境中,该环境的扩展程度绝对足以完成任务。
使用 SvcTraceViewer.exe 使用(e2e-file)检查跟踪日志时,问题似乎是这样的:
读取流时抛出异常。
使用调用堆栈:
System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.Read(Byte[] buffer, Int32 offset, Int32 count)
DataService.TransferService.UploadFile(RemoteFileInfo request)
SyncInvokeUploadImage(Object , Object[] , Object[] )
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
服务合同如下所示:
[ServiceContract]
public interface ITransferService
{
[OperationContract]
RemoteFileInfo DownloadImage(DownloadRequest request);
[OperationContract(IsOneWay = true)]
void UploadImage(RemoteFileInfo request);
}
[MessageContract]
public class DownloadRequest
{
[MessageBodyMember]
public string FileName;
}
[MessageContract]
public class RemoteFileInfo : IDisposable
{
[MessageHeader(MustUnderstand = true)]
public string FileName;
[MessageHeader(MustUnderstand = true)]
public long Length;
[MessageBodyMember(Order = 1)]
public System.IO.Stream FileByteStream;
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
这里是服务实现:
public class TransferService : ITransferService
{
public RemoteFileInfo DownloadImage(DownloadRequest request)
{
return DownloadFile(request);
}
public void UploadImage(RemoteFileInfo request)
{
UploadFile(request);
}
public RemoteFileInfo DownloadFile(DownloadRequest request)
{
var result = new RemoteFileInfo();
try
{
var filePath = Path.Combine(RoleEnvironment.GetLocalResource("TempStorage").RootPath, request.FileName);
var fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
throw new FileNotFoundException("File not found", request.FileName);
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
result.FileName = request.FileName;
result.Length = fileInfo.Length;
result.FileByteStream = stream;
}
catch (Exception ex)
{
}
return result;
}
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream;
var sourceStream = request.FileByteStream;
var filePath = Path.Combine(RoleEnvironment.GetLocalResource("TempStorage").RootPath, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 65000;
var buffer = new byte[bufferLen];
var count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
}
我已经像这样设置了 WCF 服务的 web.config 以启用流式传输,增加相关的大小限制(或至少是我知道的限制)和超时:
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="sdt"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "log.e2e" />
</listeners>
</source>
</sources>
</system.diagnostics>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="14400" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
transferMode="Streamed" >
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
客户端是一个 WPF 应用程序。调用代码是这样的:
private void UploadImage(byte[] data, Guid guid)
{
using (var transferService = new TransferServiceClient())
using (var stream = new MemoryStream(data))
{
var uploadRequestInfo = new RemoteFileInfo();
uploadRequestInfo.FileName = guid.ToString();
uploadRequestInfo.Length = data.Length;
uploadRequestInfo.FileByteStream = stream;
transferService.UploadImage(uploadRequestInfo);
}
}
private byte[] DownloadImage(Guid guid)
{
using (var transferService = new TransferServiceClient())
{
try
{
var request = new DownloadRequest(guid.ToString());
var iconFile = transferService.DownloadImage(request);
var data = ByteArrayOperations.FromStream(iconFile.FileByteStream);
return data;
}
catch (Exception)
{
return null;
}
}
}
最后 - 客户端 app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<system.web>
<httpRuntime maxRequestLength="2097150"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITransferService"
closeTimeout="04:01:00"
openTimeout="04:01:00"
receiveTimeout="04:10:00"
sendTimeout="04:01:00"
allowCookies="false"
bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
messageEncoding="Text"
textEncoding="utf-8"
transferMode="Streamed"
useDefaultWebProxy="true">
<readerQuotas maxDepth="128"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None"
proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="xxx/TransferService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService"
contract="Transfer.ITransferService" name="BasicHttpBinding_ITransferService" />
</client>
</system.serviceModel>
</configuration>
请注意,出于绝望,我添加了此部分:
<system.web>
<httpRuntime maxRequestLength="2097150"/>
</system.web>
没有任何影响。
在错误日志中,启动服务后直接抛出了另一个异常。我不知道它是什么意思,也不知道它是否与问题有关:
System.ServiceModel.ProtocolException
内容类型多部分/相关; type="application/xop+xml";start="http://tempuri.org/0>";boundary="uuid:b230e809-500b-4217-a08e-32ff49e13bac+id=5";start-info="text/xml" 被发送到需要 text/xml 的服务;字符集=utf-8。客户端 和服务绑定可能不匹配。
我已经花了好几天的时间让这个工作,真的不知道我还能尝试什么。如果有人可以查看配置并提示您还有什么可以尝试的,我会非常高兴。所以,问题是:
传输失败的原因可能是什么?我可以做些什么来解决这个问题?
我也很乐意提供进一步的建议
如果无法根据问题中提供的信息确定问题的根源,如何在此处找到根本问题?
附录:我认为客户端异常没有任何用处,但我想将其包含在问题中,以便其他有相同问题的人更容易找到答案(希望如此):
“System.Net.Sockets.SocketException”类型的第一次机会异常 发生在 System.dll 中
附加信息:现有连接被强行关闭 远程主机
【问题讨论】:
-
我对您的服务配置文件感到困惑。
system.ServiceModel下不应该有Services节点吗? -
您好 Andrew,非常感谢您关注这个巨大的问题。我对这个 WCF 东西不是很熟悉,但我认为配置不需要这个,因为该服务托管在 Azure WebRole 中,并且角色会处理这个问题。不过我可能是错的。尽管这是托管在 WebRole 中,但我是否遗漏了什么?
-
对不起,我不能帮助 Marc,我不是真正的 Azure 人。
-
没问题,谢谢你,安德鲁!