我正在尝试通过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
内容类型multipart / related; 类型= “应用/ XOP + xml” 的;开始= “&LT; http://tempuri.org/0>”;边界= “UUID:b230e809-500b-4217-a08e-32ff49e13bac + ID = 5”;启动信息=“文本/ XML” 被发送到期望text / xml的服务;字符集= UTF-8。客户端 和服务绑定可能不匹配。
我花了好几天才开始工作,真的不知道我还能尝试什么。如果有人可以看看这些配置并且可能会提示还有什么可以尝试,我会非常高兴。所以,问题是:
导致转移失败的原因是什么?我该怎么做才能解决这个问题?
我也很乐意为
提供进一步的建议如果根据问题中提供的信息无法识别根本问题该怎么办?
附录:我不认为客户端例外有任何用处,但我想将其包含在问题中,以便其他有相同问题的人更容易找到答案(希望如此):
“System.Net.Sockets.SocketException”类型的第一次机会异常 发生在System.dll
中其他信息:现有连接被强行关闭 远程主机
答案 0 :(得分:1)
我没有看到在serivce配置文件中指定服务绑定的位置。我怀疑配置值没有被读取,这就是原因。
所以我建议将服务配置文件中的绑定名称指定为BasicHttpBinding_ITransferService
(客户端配置中使用的相同名称),然后在配置文件的system.serviceModel
节点下添加以下内容:
<services>
<service name="TransferService" >
<endpoint
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITransferService"
contract="Transfer.ITransferService" />
</service>
</services>