1

我已经创建了 WCF 服务并将其托管到 IIS 中。我使用此 WCF 服务将文件从客户端机器上传到服务器。在这项服务中,我将多个图像文件上传到服务器,但是当图像文件大小为 MB(例如 6MB)时,它会给我一个错误“CommunicationException was Unhandled”

An error occurred while receiving the HTTP response to http://localhost:50904

/Transferservice.svc. This could be due to the service endpoint binding not using the HTTP 

protocol. This could also be due to an HTTP request context being aborted by the server 

(possibly due to the service shutting down). See server logs for more details.

堆栈跟踪

Server stack trace: 
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at WindowsForms.TransferServiceReference1.ITransferService.UploadFile(RemoteFileInfo request)
   at WindowsForms.TransferServiceReference1.TransferServiceClient.WindowsForms.TransferServiceReference1.ITransferService.UploadFile(RemoteFileInfo request) in F:\TransferServiceReference1\Reference.cs:line 206
   at WindowsForms.Form1.btnUpload_Click(Object sender, EventArgs e) in F:\Project Under Amit Sir\WindowsForms\WindowsForms\Form1.cs:line 37
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at WindowsForms.Program.Main() in F:\Project Under Amit Sir\WindowsForms\WindowsForms\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

WCF 服务代码

ITransferService.cs

 [ServiceContract]
    public interface ITransferService
    {
           [OperationContract]
           void  UploadFile(RemoteFileInfo request);
    }

    [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;
            }
        }
    }

服务1.cs

public class Service1 : ITransferService
    {
public void UploadFile(RemoteFileInfo request)
        {
            FileStream targetStream = null;
            Stream sourceStream = request.FileByteStream;

                    string uploadFolder = @"D:\upload\FileName\";

            string filePath = Path.Combine(uploadFolder, request.FileName);

            using(targetStream = new FileStream(filePath, FileMode.Create,
                                  FileAccess.Write, FileShare.None))
            {
                //read from the input stream in 65000 byte chunks
                            const int bufferLen = 65000;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
            while((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    // save to output stream
                    targetStream.Write(buffer, 0, count);
                }
                targetStream.Close();
                sourceStream.Close();
            }
        }
}

网络配置

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>

  </system.web>
  <system.serviceModel>

    <!--<bindings>
      <basicHttpBinding>
        <binding name="TansferService.Service1Behavior" messageEncoding="Text" transferMode="Streamed" maxReceivedMessageSize="4294967294"
                 maxBufferSize="65536" maxBufferPoolSize="65536">
        </binding>
      </basicHttpBinding>
    </bindings>-->

    <services>
      <service behaviorConfiguration="TansferService.Service1Behavior" name="TansferService.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="TansferService.ITransferService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/TransferService.svc"/>
          </baseAddresses>
        </host>
      </service>
    </services>    
     <behaviors>
      <serviceBehaviors>
        <behavior name="TansferService.Service1Behavior">
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

客户端的客户端代码 只是单个上传按钮此上传按钮使用 WCF 服务代码将多个文件传输到服务器

private void btnUpload_Click(object sender, EventArgs e)
        {
            DirectoryInfo dir = new DirectoryInfo(Application.StartupPath+@"\Upload Files");

            TransferServiceClient obj = new TransferServiceClient();
            ITransferService clientUpload = new TransferServiceClient();
            RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();
            foreach (FileInfo fileInfo in dir.GetFiles())
            {
                string fileName = Path.Combine(fileInfo.DirectoryName , fileInfo.ToString());           
                using (FileStream stream = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    uploadRequestInfo.FileName = fileInfo.ToString();
                    uploadRequestInfo.Length = fileInfo.Length;
                    uploadRequestInfo.FileByteStream = stream;
                    clientUpload.UploadFile(uploadRequestInfo);
                }
            }
        }

应用程序配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_ITransferService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="4294967294"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
                <binding name="BasicHttpBinding_ITransferService1" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:50904/Transferservice.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService"
                contract="TransferServiceReference.ITransferService" name="BasicHttpBinding_ITransferService" />
            <endpoint address="http://localhost:50904/Transferservice.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService1"
                contract="TransferServiceReference1.ITransferService" name="BasicHttpBinding_ITransferService1" />
        </client>
    </system.serviceModel>

</configuration>
4

3 回答 3

1

尝试使用MSDN中的以下配置打开 WCF 跟踪,以调查幕后发生的事情并发现引发的异常;因为您遇到的异常是一般异常,并没有告诉您问题的确切来源。

<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="CardSpace">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.IO.Log">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.Runtime.Serialization">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.IdentityModel">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
        </sources>

        <sharedListeners>
            <add name="xml"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="c:\log\Traces.svclog" />
        </sharedListeners>
    </system.diagnostics>
</configuration>
于 2013-07-01T13:54:06.137 回答
1

出于测试目的,您可以在故障中包含服务器异常详细信息。

在你的 web.config 中改变这个:

<serviceDebug includeExceptionDetailInFaults="false"/>

至:

<serviceDebug includeExceptionDetailInFaults="true"/>

更多详细信息:http: //msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedebugbehavior.includeexceptiondetailinfaults.aspx

于 2013-07-01T16:40:37.390 回答
0

试试这个设置:

<system.web>    
<httpRuntime maxRequestLength="102400" />
</system.web>

这会将最大消息长度设置为 100 MB。查看此MSDN 页面以获取更多信息。

于 2013-07-01T13:37:49.350 回答