2009-07-22 13 views
14

.Net'den bir web sunucusuyla iletişim kurarım. Web sunucusu 500 dahili sunucu hatası veriyor ve ayrıntılı bir hata mesajı yazıyor.WebException bir WebException'ın yanıt akışını okurken

Web istisnasından alınan hata mesajını okumaya çalışıyorum, ancak başka bir web istisnası alıyorum. İkinci WebException neden atılıyor?

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

cevap

12

Bu neden şaşırtıcı? MSDN'den aşağıdaki deneyin:

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

AMM, aslında her nasılsa tel üzerinden iletilen hata mesajını okumak istiyorum çünkü. Web sitesi mevcut değil, istemci tarafında kayıt/analiz etmek istediğim bir hata ile cevap veriyor. – ripper234

+0

Web sitesi uygunsuzsa, hatanın nereden geldiğini öğrenin? Her halükarda güncellenir. –

+1

Bu _not_ varolmayan :) – ripper234

İlgili konular