Search code examples
c#asmxwebservice-client

Underlying connection closed exception thrown in web service call


I know this question has been asked before, and many suggestions have been made, but I have tried all of them and none worked, so I am trying to see if anyone has extra knowledge on this matter.

Scenario: I have a console application in which I have added a web reference to an ASMX web service. In the console app I have generated a derived class like this:

public class OverridenWebRequestReporting : webservice.Reporting
{
    public OverridenWebRequestReporting(string addr)
        : base(addr)
    {
    }

    protected override System.Net.WebRequest GetWebRequest(Uri uri)
    {
        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
        webRequest.KeepAlive = false;
        webRequest.ProtocolVersion = HttpVersion.Version10;
        webRequest.ServicePoint.ConnectionLimit = 1;
        return webRequest;
    }
}

The call to the web service method is the following:

        OverridenWebRequestReporting reportingService = new OverridenWebRequestReporting("http://some_web_location_where_the_service_is_deployed/Reporting.svc");

        CredentialCache cache = new CredentialCache();

        cache.Add(new Uri("http://some_web_location_where_the_service_is_deployed/Reporting.svc"), "NTLM",new NetworkCredential("username", "password", "domain"));

        reportingService.Credentials = cache;

        System.Net.ServicePointManager.Expect100Continue = false;

        DataTable dt = new DataTable();

        using (reportingService)
        {
            try
            {
                dt = reportingService.GetAllDocumentsMetadataFromSP("someString", "anotherString");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

        }

Using the debugger, I can clearly see that the call is made, and it returns a valid datatable, but when the last return statement is made, the code enters the catch block, with an exception of "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server." being thrown

Framework is 4.5.

Any suggestions in what else can I do to prevent the exception from being thrown?


Solution

  • The solution is a combination of changes:

    1) Adding, as Kirill suggested, a name to the datatable

    2) Using dt.WriteXml(writer, XmlWriteMode.WriteSchema, false); in the service, to generate an XML string

    3) Using

    using (StringReader r = new StringReader(XMLSerializedResult))
            {
                dt.ReadXml(XmlReader.Create(r));
            }
    

    in the client to deserialize the XML string.

    Thank you all for the suggestions.