远程主机强行关闭现有连接(" CommunicationException为Unhandled")

时间:2013-07-01 13:31:57

标签: c# wcf

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

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

Service1 .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();
            }
        }
}

的Web.Config

<?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);
                }
            }
        }

App.Config中

<?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>

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

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

你的web.config中的

改变了这个:

<serviceDebug includeExceptionDetailInFaults="false"/>

为:

<serviceDebug includeExceptionDetailInFaults="true"/>

此处有更多详情: http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedebugbehavior.includeexceptiondetailinfaults.aspx

答案 2 :(得分:0)

尝试以下设置:

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

这会将最大邮件长度设置为100 MB。有关详细信息,请查看此MSDN page