title: .NET HttpClient - An existing connection was forcibly closed by the remote host
body: <p>I have this code called from an ASP.NET MVC controller:</p>
  
  <pre><code>protected string PostData(string url, ByteArrayContent content)
          {
              using (var client = new HttpClient())
              {
                  client.Timeout = TimeSpan.FromDays(1);
                  return client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
              }
          }
  </code></pre>
  
  <p>If I am posting data to a REST service which takes some time to execute, I get this error:</p>
  
  <pre><code>System.AggregateException: One or more errors occurred. ---&gt; System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
     at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
     at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
     --- End of inner exception stack trace ---
     at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
     at System.Net.PooledStream.EndRead(IAsyncResult asyncResult)
     at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
     --- End of inner exception stack trace ---
     at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
     at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
     --- End of inner exception stack trace ---
     --- End of inner exception stack trace ---
     at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
     at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
     at System.Threading.Tasks.Task`1.get_Result()
     at Libcor.Services.Ssp.External.ExternalServiceBase.PostData(String absoluteUrl, ByteArrayContent content)
  </code></pre>
  
  <p>The REST service still completes it's work in the background but the ASP.NET MVC gets this exception. Works fine for shorter running services. How do I prevent this from happening?</p>