C# WCF 底层连接已关闭:接收时发生意外错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15858784/
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 18:11:24  来源:igfitidea点击:

WCF The underlying connection was closed: An unexpected error occurred on a receive

c#wcfwcf-rest

提问by Millar

I am using a RestClient app to communicate with my WCF service .and I am getting the following exception

我正在使用 RestClient 应用程序与我的 WCF 服务进行通信。我收到以下异常

The underlying connection was closed: An unexpected error occurred on a receive.

This is the C# code I use

这是我使用的 C# 代码

            string q = string.Format(@"xxxxxxxxxxxxxxxxxxxxxxxxxxx");
            WebClient client = new WebClient();
            string Url = string.Format("{0}/Get?queries={1}", BaseUrl,HttpUtility.UrlEncodeUnicode(q));
            client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
            var result = client.DownloadString(Url);
            Console.WriteLine("======================output================================");
            Console.WriteLine(result);
            Console.WriteLine("===========================================");

Here is the error message

这是错误信息

System.Net.WebException was caught
  HResult=-2146233079
  Message=The underlying connection was closed: An unexpected error occurred on a receive.
  Source=System
  StackTrace:
       at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
       at System.Net.WebClient.DownloadString(Uri address)
       at System.Net.WebClient.DownloadString(String address)
       at RestClient.Program.GetRecordsTest() in C:\Users\Wiemon\Downloads\RestAppClient\RestAppClient\Program.cs:line 118
  InnerException: System.IO.IOException
       HResult=-2146232800
       Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
       Source=System
       StackTrace:
            at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
            at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
            at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
            at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
            at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
            at System.Net.Security._SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
            at System.Net.TlsStream.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)
       InnerException: System.Net.Sockets.SocketException
            HResult=-2147467259
            Message=An existing connection was forcibly closed by the remote host
            Source=System
            ErrorCode=10054
            NativeErrorCode=10054
            StackTrace:
                 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)
            InnerException: 

Here is my binding

这是我的绑定

<binding name="wsHttpEndpoint" >
                    <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                    <security mode="Transport">
                        <transport clientCredentialType="Certificate" />
                        <message clientCredentialType="Certificate" />
                    </security>
                </binding>

And my endpoint behavior ,not that I set maxItemsInObjectGraph="2147483647"

而我的端点行为,并不是我设置了 maxItemsInObjectGraph="2147483647"

<behavior name="MyEndpointBehavior">
                    <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                    <clientCredentials>
                        <clientCertificate findValue="xxxxxxxxxxxxxxxxxx" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
                        <serviceCertificate>
                            <authentication certificateValidationMode="None" revocationMode="NoCheck" />
                        </serviceCertificate>
                    </clientCredentials>
                </behavior>

采纳答案by evgenyl

Its common (generic) message.

它的通用(通用)消息。

You should use Trace Viewer Tool(SvcTraceViewer.exe) to find out server error

您应该使用Trace Viewer Tool(SvcTraceViewer.exe) 来找出服务器错误

回答by David Beavon

I had similar errors coming from the depths of my http bindings in WCF.

我有类似的错误来自 WCF 中 http 绑定的深度。

client -> The underlying connection was closed: An unexpected error occurred on a receive.

客户端 -> 底层连接已关闭:接收时发生意外错误。

client -> Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

客户端 -> 无法从传输连接读取数据:远程主机强行关闭了现有连接。

server (got this with the help of "procdump") -> The I/O operation has been aborted because of either a thread exit or an application request

服务器(在“procdump”的帮助下得到这个)-> 由于线程退出或应用程序请求,I/O 操作已中止

Eventually after many hours I came upon the HTTP.sys logging (in C:\WINDOWS\System32\LogFiles\HTTPERR ) and I discovered that the WCF self-hosted service connections were being forcibly dropped (on purpose) because of an obscure configuration issue (minimum send rate bytes per second). Unfortunately it took another few hours to reconfigure that (you cannot do it via "netsh http add timeout" so you have to do it within the app or within IIS when not self-hosted).

最终,几个小时后,我发现了 HTTP.sys 日志记录(在 C:\WINDOWS\System32\LogFiles\HTTPERR 中),我发现 WCF 自托管服务连接由于一个模糊的配置问题而被强行删除(故意) (每秒最小发送速率字节)。不幸的是,重新配置它又花了几个小时(你不能通过“netsh http add timeout”来完成,所以你必须在应用程序中或在非自托管时在 IIS 中完成)。

回答by gatsby

I dont't know if is the same error, but in my case, the exception was in Json, that cannot convert the Date value, because it was empty.

我不知道是否是相同的错误,但在我的情况下,异常在 Json 中,无法转换 Date 值,因为它是空的。

DateTime values that are greater than DateTime.MaxValue or smaller than DateTime.MinValue when converted to UTC cannot be serialized to JSON.

转换为 UTC 时大于 DateTime.MaxValue 或小于 DateTime.MinValue 的 DateTime 值无法序列化为 JSON。

The trace viewer was very useful to find the issue.

跟踪查看器对于查找问题非常有用。

回答by flam3

Configure WCF tracing in your app.config / web.config and check Error.svclog(it will be created near your binary file) for details. In my case it was because of using Auto-property initializer (property without setter) - a feature from C# 6.0

在 app.config / web.config 中配置 WCF 跟踪并检查Error.svclog(它将在您的二进制文件附近创建)以了解详细信息。就我而言,这是因为使用了自动属性初始化程序(没有 setter 的属性)—— C# 6.0 的一项功能

<Message>No set method for property 'FailedCount' in type 'MyProject.Contracts.Data.SyncStatusByVersion'.</Message>
<StackTrace>   at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
               at WriteSyncStatusByVersionToJson(XmlWriterDelegator , Object , XmlObjectSerializerWriteContextComplexJson , ClassDataContract , XmlDictionaryString[] )
               ...
</StackTrace>

To configure WCF tracing:

要配置 WCF 跟踪:

<system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true" >
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource" switchValue="Information, ActivityTracing">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Error.svclog" />
    </sharedListeners>
</system.diagnostics>