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

本文关键字:错误 意外 连接 | 更新日期: 2023-09-27 18:07:56

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

The underlying connection was closed: An unexpected error occurred on a receive.
这是我使用的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("===========================================");

下面是错误信息

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: 

这是我的绑定

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

我的端点行为,而不是我设置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>

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

常见(通用)消息

您应该使用跟踪查看器工具(SvcTraceViewer.exe)来查找服务器错误

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

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

client ->无法从传输连接中读取数据:远程主机强制关闭了现有连接。

server(在"procdump"的帮助下)->由于线程退出或应用程序请求,I/O操作已被终止

最终经过几个小时后,我来到了HTTP。我发现WCF自托管服务连接被强制(故意)丢弃,因为一个模糊的配置问题(每秒最小发送速率字节数)。不幸的是,它又花了几个小时来重新配置(你不能通过"netsh http add timeout"这样做,所以你必须在应用程序或IIS内做,当不是自托管的)。

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

DateTime大于DateTime的值。MaxValue或小于DateTime。MinValue转换为UTC时不能序列化为JSON

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

在app.config/web中配置WCF跟踪。config and check 错误。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>

配置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>