6

ここに実装されている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

Web サービスに xml リクエストを送信しています。私の send メソッドは次のようになります。

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

1 に答える 1

11

問題は、コードのこの部分にあります。

// 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);
于 2012-06-22T17:56:05.340 に答える