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

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.