请求已中止:连接意外关闭

时间:2012-06-22 17:47:53

标签: c# asp.net web-services httpwebrequest

我正在使用Jon Skeet在这里实现的ReadFully方法:

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);
        }
    }
}

它在该行引发异常:

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

错误讯息为The request was aborted: The connection was closed unexpectedly

我正在向webservice发送xml请求。我的发送方法如下所示:

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;
}

我试过没有和没有设置以下变量,它给了我相同的信息:

req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;

1 个答案:

答案 0 :(得分:9)

问题在于您的代码的这一部分:

// 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);

在从流中读取之前,您将处置响应对象。尝试这样的事情:

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);