2012-06-22 88 views
3

我使用實施這裏全碟的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請求。我的發送方法是這樣的:

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; 

回答

8

的問題是在這部分代碼:

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

你真棒。這工作。我想這是我得到的信賴Resharper太多。 – Xaisoft

相關問題