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

4

9

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

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

This is the C# code I use

            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"

<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>
Deason answered 7/4, 2013 at 4:13 Comment(0)
G
11

Its common (generic) message.

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

Gerrygerrymander answered 7/4, 2013 at 4:28 Comment(1)
Thank you. As you suggested,I enabled tracing , then scanned through the logs using Traceviewer tool .This helped me to identify the problem.Deason
H
6

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

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

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

Headley answered 10/9, 2015 at 12:46 Comment(2)
Can you elaborate on the solution? Do you have any reference that might be usefull?Mahmoud
I have a support case open with Microsoft and they say there may be a breaking change in Windows 2012 R2 related to one of the HTTP.sys timeouts (minimum send rate bytes per second). It is primarily experienced on a slow wan connection. I moved this discussion to social.msdn.microsoft.com (search "WCF Errors on MinSendBytesPerSecond")Headley
P
3

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.

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

The trace viewer was very useful to find the issue.

Praemunire answered 11/1, 2016 at 18:18 Comment(0)
U
1

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

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

<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>
Uzia answered 18/1, 2018 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.