By jonho


2015-10-20 10:07:57 8 Comments

I am using the HttpClient class in .Net 4.5.2 framework. I am doing a PostAsync to a third party web service. 80% of the time this post works, 20% of the time our response is cut short. In this situation we get the following exception:

System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> 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.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) at System.Net.FixedSizeReader.StartReading() 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.TlsStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback asyncCallback, Object asyncState) at System.Net.ConnectStream.BeginReadWithoutValidation(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) at System.Net.ConnectStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) at System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) at System.Net.Http.StreamToStreamCopy.StartRead()

A subsequent identical request succeeds. It is not a request we can retry as the business has already been placed. So it leaves us in an awkward situation.

This is my code:

using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Authorization = authorizationHeader;
    HttpContent httpContent = new StringContent(someXml);

    //Exception occurs on next line...
    var response = await httpClient.PostAsync("https://thirdpartyendpoint", httpContent);
    var responseXml = await response.Content.ReadAsStringAsync();  
    //convert to Dto              
}

The third party service are successfully saving the record to their database and do not see any obvious exceptions at their end. They did note that the failing requests generally took longer (around 18-30 seconds) to write to the database than the successful requests.

Thankyou for your help

1 comments

@jonho 2015-11-03 14:32:57

we resolved this problem with 2 code changes:

  1. Dispose of the httpResponseMessage and just work with a simple DTO

     using (var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage))
        {
            return await CreateDto(httpResponseMessage);
        }
    
  2. Downgrade the version of HTTP to v1.0

    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(url))
    {
        Version = HttpVersion.Version10,
        Content = httpContent
    };
    
    await client.SendAsync(httpRequestMessage);
    

which has the effect of adding this Http header

    Connection: close 

rather than this

    Connection: keep-alive

@garenyondem 2016-03-07 13:38:55

Any ideas about how to apply HttpVersion to httpClient get requests?

@jonho 2016-03-14 22:18:30

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(url)) { Version = HttpVersion.Version10, Content = httpContent }; await client.SendAsync(httpRequestMessage); should do it

@Baqer Naqvi 2016-05-18 10:35:35

worked for me.thanks

@zinczinc 2018-05-20 23:06:26

Using DTOs instead solved my problem. I suspected it would help. Thank you!

@juanora 2018-05-29 13:30:41

just by changing DefaultRequestHeaders.ConnectionClose to true worked for me :)

Related Questions

Sponsored Content

5 Answered Questions

[SOLVED] Getting EOF exception over https call

  • 2011-03-21 19:26:15
  • Amzath
  • 25259 View
  • 12 Score
  • 5 Answer
  • Tags:   .net http

0 Answered Questions

Handle "Error while copying content to a stream" Exception

  • 2018-07-30 06:58:58
  • exe
  • 354 View
  • 1 Score
  • 0 Answer
  • Tags:   c#

3 Answered Questions

[SOLVED] System.IO.IOException: The handshake failed due to an unexpected > packet format?

  • 2011-03-03 09:21:56
  • TheLearner
  • 34853 View
  • 18 Score
  • 3 Answer
  • Tags:   c# wcf

0 Answered Questions

WCF service - connection was forcibly closed by the remote host

  • 2014-06-12 13:32:11
  • SelvirK
  • 2395 View
  • 0 Score
  • 0 Answer
  • Tags:   c# asp.net .net wcf

0 Answered Questions

PowerShell + HttpWebRequest throws exception

0 Answered Questions

The message received was unexpected or badly formatted

2 Answered Questions

[SOLVED] Accessing Webservice which is hosted on https server

1 Answered Questions

How do access a secure website within a sharepoint webpart?

Sponsored Content