February 2008
Posted on the 16th at 12:51 AM CST
The Underlying Connection was Closed - How to Fix This Pesky ASP.NET WebException
FiledFiled under ASP.NET, VB.NET

If your ASP.NET application calls a web service (you have a reference in your App_WebReferences folder), you might come across this fairly typical System.Net.WebException. I have seen two different breeds of this exception, and the solutions for each of them are quite similiar. I will start off with the most common of the two.

The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.

This is the one you are most likely to see, and the fix for this is simple and generally well-known. You need to create a class that inherits your web service class. Then you simply override the GetWebRequest function and modify the KeepAlive HTTP header accordingly…

Public Class MyWebService
    Inherits ServiceName.WebService

    Protected Overrides Function GetWebRequest(ByVal uri As Uri) As System.Net.WebRequest
        Dim webRequest As System.Net.HttpWebRequest = MyBase.GetWebRequest(uri)

        webRequest.KeepAlive = False

        Return webRequest
    End Function
End Class


Simple as that. When you need to invoke the web service elsewhere in your code, just instatiate that class instead of what you would do normally…

Dim Response as String

Using MyService as New MyWebService()
    Response = MyService.METHOD_NAME("MethodInput")
End Using


And that takes care of that exception.

The underlying connection was closed: The connection was closed unexpectedly.

Sometimes, using the solution above will cause this exception. I believe that it has something to do with the way Windows Authentication is configured in IIS. I ran across a situation where I had to deploy my applicaton (with web service references) to a remote server that was not in our control; it was being hosted for us. Apparently, they were using NTLM Authentication, which requires connections to be kept-alive, hence this exception. However, using KeepAlive makes your requests totally inconsistent, in most cases. They will work one time, but will fail the next. The host was not willing to change for this for our application, obviously, so I was stuck. Finally, I was able to determine that the ConnectionGroupName property is what is used to re-establish the connection that was supposed to be "kept alive". So, you can just set that property to a random value (GUID), in the same way that I set the KeepAlive property above…

Public Class MyWebService
    Inherits ServiceName.WebService

    Protected Overrides Function GetWebRequest(ByVal uri As Uri) As System.Net.WebRequest
        Dim webRequest As System.Net.HttpWebRequest = MyBase.GetWebRequest(uri)

        webRequest.ConnectionGroupName = Guid.NewGuid().ToString()

        Return webRequest
    End Function
End Class


Problem solved; that worked fantastic! I hope this has helped you out, and I also hope that I have had my final bout with the System.Net.WebException.

Comments (15)
Permalink Comment from An old hacker on May 16th, 2008 at 10:19 AM
Recent studies from independant companies proved that even if IE has more security problem, those problems are minor, Firefox security problems are less in number but by far a worst threat (hackers could take control of the user system)

But I guess that you're not able to program correctly for multiple browsers.
Permalink Comment from Josh StodolaEmail on May 16th, 2008 at 11:58 AM
Pardon? I don't know what the hell you are talking about! I am able to "program correctly" for all modern browsers. Regardless, that has nothing to do with your first statement. Keep your comments constructive, please.
Permalink Comment from Az on July 31st, 2008 at 10:57 PM
Thanks - this solved an issue that had been bugging me for ages...
Permalink Comment from Brandon on November 4th, 2008 at 4:52 PM
Thanks for the insight. This resolved flaky connection issues with a client of mine who was consuming one of my web services using WSE 3 security.
Permalink Comment from Pratik Patel on December 9th, 2008 at 2:54 PM
I have a Windows Webservice that talks to a Peoplesoft webservice in one of the applications and that's where I receive this error.

Although there are many other applications that talk to Peoplesoft in the EXACTLY same way but I get this error frequently for the only latest application.

ConnectionGroupName or KeepAlive property is NOT set on any of them.
Permalink Comment from ApeterEmail on December 10th, 2008 at 12:51 PM
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.

I have the same above error. Can you please tell me how this keep alive error can happen when i make one request/call to a web service ?

-Thanks.
Permalink Comment from Josh StodolaEmail on December 10th, 2008 at 12:56 PM
It happens because the web service proxy class sends the KeepAlive HTTP header by default (inside an instance of the WebRequest class). To prevent this, follow the instructions in the post and set the KeepAlive property to false.

Brief description of KeepAlive: http://www.io.com/~maus/HttpKeepAlive.html

Hope this helps!
Permalink Comment from Ranjit SinghEmail on April 14th, 2009 at 12:33 PM
your website is very good looking.
Permalink Comment from Gramps on May 11th, 2009 at 1:39 PM
Regarding your cute script that abuses people with unworthy browser/versions. Some of us are stuck using a shop standard, enforced by Network Nazis, which is bad enough without you crapping on us to boot.
Permalink Comment from Josh StodolaEmail on May 11th, 2009 at 3:39 PM
I understand, gramps, and I do have sympathy for you. To hell with network nazis!
Permalink Comment from noob on May 25th, 2009 at 11:37 AM
ok where do i input this code ???? im a noob, how do i fix this, where do i save it??? ans so on
Permalink Comment from Pawan Gupta on October 21st, 2009 at 4:49 AM
I was facing the same issue( System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.). After lot of troubleshooting I found that somehow the host file under C:\WINDOWS\system32\drivers\etc was changed and was containing wrong IP Address for my site. After I corrected it to point to right one it started working.

Hope this helps!!!
Permalink Comment from + on January 12th, 2010 at 7:13 AM
hhhhmmm
Permalink Comment from bvjn on January 12th, 2010 at 7:14 AM
xfg hfdh dfh df hdf
Permalink Comment from chuck on January 19th, 2010 at 5:29 PM
I'm getting this exception periodically while calling a 3rd party control that in turn hits a web service. My solution references only a dll, there is no web reference to the actual web service. Here is the 1 line of code that calls the method in the dll.

Dim loc() As CityStateLocations = AssistedSolutions.WebControls.CityStateFinder.CityStateFinder.SearchOn("92880")


Is there any way I can implement your keepalive solution?

Guess What?

There are a few basic guidelines you should be aware of before leaving a comment…

  • If you choose to display your email address, it will not be detected by spam bots
  • Comments are limited to 3,000 characters; so far you have used none of them
  • HTML will be encoded; links and line breaks will be converted automatically
  • Comments containing five or more links will be subject to moderation

Have Your Say

← Answer this to prove you are human
 
 

Chill Out…