(Webservices) - "The underlying connection was closed: An unexpected error occurred on a send."

Sometimes when you invoke a webservice the call fails with the following exception:

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.
at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ...

In some cases the first call to the webservice works just fine, but if in the following few minutes no new call to the webservice is made, the next call would throw the exception shown above. This problem could be solved by altering the generated proxy class; in the GetWebRequest function the KeepAlive property must be set to false. This can be accomplished by following these steps:


  • Add a Web Reference using the normal way (if you haven't already added one ofcourse).
  • Make sure Show All Files menu item is enable in the Project menu.
  • In the Solution Explorer window, navigate to:

    • Web References



        • Reference.map

          • Reference.cs (or .vb)

  • Open the Reference.cs file and add following code in the webservice proxy class:
C-Sharp:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
 System.Net.HttpWebRequest webRequest =
  (System.Net.HttpWebRequest) base.GetWebRequest(uri);
 webRequest.KeepAlive = false;
 return webRequest;
VB:
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





}

Comments