Search
Close this search box.

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

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

I’ve been trying to figure out what the cause of this problem is for a few days now and I’ve finally tracked down the error.

It’s due to a bug in .net that closes the connection prior to it being finished.  I’m concerned about the performance issues involved in reconnecting, however I have written my code to keep most connections and data transfer small anyways, I’ll have to keep an eye on the performance of this crappy bug.

A good reference for solving this issue is available at: http://p2p.wrox.com/topic.asp?TOPIC_ID=4858

Unfortunately the microsoft KB article that addressed the issue is no longer available.

As suggested I have added the following code to my reference.cs file (which needs to be done each time I update the webservice reference) to assign the keepalive value to false to allow the connection to be closed and reopened.

protected override WebRequest GetWebRequest(Uri uri)

{
  HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);

  webRequest.KeepAlive = false;
  webRequest.ProtocolVersion = HttpVersion.Version10;
  return webRequest;
}

I have also added a reference to System.Net via a using statement to import the HttpWebRequest namespace.

This article is part of the GWB Archives. Original Author: Denis Pitcher

Related Posts