C# System.ServiceModel.CommunicationException:底层连接已关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19518978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:10:45  来源:igfitidea点击:

System.ServiceModel.CommunicationException: The underlying connection was closed

c#asp.net.netwcfsockets

提问by user2907164

I am retrieving data from a wcf web service and when data is more than 0.2 million records i get an exception which is as under:

我正在从 wcf Web 服务中检索数据,当数据超过 20 万条记录时,我收到如下异常:

System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---

Server stack trace: 
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.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.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

My web.config looks like this :

我的 web.config 看起来像这样:

<basicHttpBinding>
  <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
             maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
             allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
             messageEncoding="Text" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true">
    <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                  maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
    <security mode="None">
      <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />
    </security>
  </binding>
  <binding maxReceivedMessageSize="2147483647" allowCookies="true">
    <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
  </binding>
</basicHttpBinding>

I am sure that my web service is retrieving data from DB. but is unable to transfer to my web from where i initiated the call. Thanks in advance for any help.

我确信我的 Web 服务正在从数据库检索数据。但无法从我发起呼叫的地方转移到我的网络。在此先感谢您的帮助。

采纳答案by costa

I had recently the same problem with a Wcf service within a .Net 4.0 web app. I increased the maxItemsInObjectGraph value and server didn't throw the exception anymore. The documentation heresays the default maximum is Int32.MaxValue but I think it is incorrect, the maximum value is 65535.

我最近在 .Net 4.0 Web 应用程序中的 Wcf 服务遇到了同样的问题。我增加了 maxItemsInObjectGraph 值,服务器不再抛出异常。这里的文档说默认最大值是 Int32.MaxValue 但我认为这是不正确的,最大值是 65535。

   <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="6553500"/>
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>

The other thing you can do is enable tracing. This is an example of what I have in the web.config:

您可以做的另一件事是启用跟踪。这是我在 web.config 中的示例:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel"
            switchValue="Information, ActivityTracing"
            propagateActivity="true">
      <listeners>
        <add name="traceListener"
            type="System.Diagnostics.XmlWriterTraceListener"
            initializeData= "c:\temp\log\Traces.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

If you double click on the Traces.svclog, windows should open the Microsoft Service Trace Viewer.

如果双击 Traces.svclog,Windows 应打开 Microsoft 服务跟踪查看器。

If you test your service with the Microsoft WCF Test Client make sure you change the default client config to match the server settings (this includes the client endpoint behavior) to make sure the client can receive the response from the server.

如果您使用 Microsoft WCF 测试客户端测试您的服务,请确保更改默认客户端配置以匹配服务器设置(这包括客户端端点行为),以确保客户端可以接收来自服务器的响应。

I hope this helps.

我希望这有帮助。

回答by Peter

Make your client basicHttpBinding the same as your server binding. This is a verry common error to only change one binding instead of server and client binding.

使您的客户端 basicHttpBinding 与您的服务器绑定相同。这是一个非常常见的错误,只更改一个绑定而不是服务器和客户端绑定。

If that not works you can enable wcf tracing: wcf tracing

如果这不起作用,您可以启用 wcf 跟踪: wcf 跟踪

That will give you more insights in what the underling problem is.

这将使您更深入地了解底层问题是什么。

回答by matao

we had a loop in our object graph that were returning. I know this probably isn't your problem but I'm adding it here in case anyone else has the same problem. We had includeExceptionDetailInFaults enabled but weren't getting the error in any client (our application or the WCF Test Client). Luckily it showed up in server logs so we were able to find it that way.

我们的对象图中有一个循环正在返回。我知道这可能不是你的问题,但我在这里添加它以防其他人有同样的问题。我们启用了 includeExceptionDetailInFaults 但没有在任何客户端(我们的应用程序或 WCF 测试客户端)中收到错误消息。幸运的是它出现在服务器日志中,所以我们能够通过这种方式找到它。

We had Parent -> child and child -> parent for two-way navigation, we had to break that link and instead have parent -> child, and the child had an id to lookup the parent, then the error went away.

我们有 Parent -> child 和 child -> parent 用于双向导航,我们不得不断开该链接,而是让 parent -> child,并且 child 有一个 id 来查找 parent,然后错误消失了。

Hope this helps someone!

希望这可以帮助某人!

回答by Serkanb

Add following configuration to your wcf service config. And see c:\log\Traces.svclog file. My exception was throw for ;

将以下配置添加到您的 wcf 服务配置中。并查看 c:\log\Traces.svclog 文件。我的异常是 throw for ;

There was an error while trying to serialize parameter The InnerException message was 'Enum value '0' is invalid for type 'ThyCams2014.XrmBase.new_filingstatu' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attrienter code herebute.'. Please see InnerException for more details.

尝试序列化参数时出现错误 InnerException 消息是“枚举值 0”对于类型“ThyCams2014.XrmBase.new_filingstatu”无效并且无法序列化。如果类型具有 DataContractAttribute attrienter 代码,请确保存在必要的枚举值并使用 EnumMemberAttribute 属性标记。'。有关更多详细信息,请参阅 InnerException。

<configuration>
   <system.diagnostics>
      <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
            <listeners>
               <add name="traceListener" 
                   type="System.Diagnostics.XmlWriterTraceListener" 
                   initializeData= "c:\log\Traces.svclog" />
            </listeners>
         </source>
      </sources>
   </system.diagnostics>
</configuration>

回答by Dumindu

This statement solved my problem:

这句话解决了我的问题:

db.ContextConfiguration.ProxyCreationEnabled = false;