2009-07-22 61 views
14

我正在通過.Net與Web服務器進行通信。 Web服務器會引發500內部服務器錯誤並寫入詳細的錯誤消息。WebException在讀取WebException的響應流時

我想讀取從Web異常收到的錯誤消息,但獲取另一個Web異常。爲什麼拋出第二個WebException?

try 
{ 
    var webResponse = (HttpWebResponse)webRequest.GetResponse(); 
} 
catch (WebException e) 
{ 
    if (e.Status == WebExceptionStatus.ProtocolError) 
    { 
    // the next line throws a web exception 
    Console.WriteLine(new StreamReader(e.Response.GetResponseStream()).ReadToEnd()); 
    } 
} 

回答

12

這是爲什麼令人驚訝?從MSDN嘗試以下內容:

try { 
    // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name. 
    HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site"); 

    // Get the associated response for the above request. 
    using (HttpWebResponse myHttpWebResponse = 
       (HttpWebResponse) myHttpWebRequest.GetResponse()) { 
     myHttpWebResponse.Close(); 
    } 
} 
catch(WebException e) { 
    Console.WriteLine("This program is expected to throw WebException on successful run."+ 
         "\n\nException Message :" + e.Message); 
    if(e.Status == WebExceptionStatus.ProtocolError) { 
     var response = ((HttpWebResponse)e.Response); 
     Console.WriteLine("Status Code : {0}", response.StatusCode); 
     Console.WriteLine("Status Description : {0}", response.StatusDescription); 

     try { 
      using (var stream = response.GetResponseStream()) { 
      using (var reader = new StreamReader(stream)) { 
       var text = reader.ReadToEnd(); 
       Console.WriteLine(text); 
      } 
      } 
     } catch (WebException ex) { 
      // Oh, well, we tried 
     } 
    } 
} 
catch(Exception e) { 
    Console.WriteLine(e.Message); 
} 
+0

嗯,因爲我想實際讀取通過線路以某種方式傳輸的錯誤消息。該網站並非不存在,它回覆了一個我想在客戶端登錄/分析的錯誤。 – ripper234 2009-07-22 20:27:57

相關問題