Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The request was aborted: The connection was closed unexpectedly

I am using Jon Skeet's ReadFully method implemented here:

public static byte[] ReadFully(Stream stream)
{
    var buffer = new byte[32768];
    using (var ms = new MemoryStream())
    {
        while (true)
        {
            int read = stream.Read(buffer, 0, buffer.Length);
            if (read <= 0)
                return ms.ToArray();
            ms.Write(buffer, 0, read);
        }
    }
}

It throws an exception at the line:

int read = stream.Read(buffer, 0, buffer.Length);

The error message is The request was aborted: The connection was closed unexpectedly.

I am sending an xml request to a webservice. My send method looks like this:

private static string SendRequest(XElement request, string url)
{
    var req = (HttpWebRequest)WebRequest.Create(url);
    req.ContentType = "application/soap+xml;";
    req.Method = "POST";
    req.KeepAlive = false;
    req.Timeout = System.Threading.Timeout.Infinite;
    req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
    req.ProtocolVersion = HttpVersion.Version10;
    req.AllowWriteStreamBuffering = false;

    using (var stm = req.GetRequestStream())
    {
        using (var stmw = new StreamWriter(stm))
        {
            stmw.Write(request.ToString());
        }
    }

    Stream responseStream;
    using (var webResponse = req.GetResponse())
    {
        responseStream = webResponse.GetResponseStream();
    }

    // Do whatever you need with the response
    var myData = ReadFully(responseStream);
    string responseString = Encoding.ASCII.GetString(myData);

    return responseString;
}

I tried without and without the following variables set and it gives me the same message:

req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;
like image 501
Xaisoft Avatar asked Jun 22 '12 17:06

Xaisoft


1 Answers

The problem is in this part of your code:

// wrong way to do it!
Stream responseStream;
using (var webResponse = req.GetResponse())
{
    responseStream = webResponse.GetResponseStream();
}

// Do whatever you need with the response
var myData = ReadFully(responseStream);

You're disposing your response object before reading from its stream. Try something like this instead:

byte[] myData;
using (var webResponse = req.GetResponse())
{
    var responseStream = webResponse.GetResponseStream();
    myData = ReadFully(responseStream);    // done with the stream now, dispose of it
}

// Do whatever you need with the response
string responseString = Encoding.ASCII.GetString(myData);
like image 108
Blindy Avatar answered Nov 15 '22 00:11

Blindy