Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

.net - WebException when reading a WebException's response stream

I'm communicating with a web server from .Net. The web server throws a 500 internal server error and writes a detailed error message.

I'm trying to read the error message that is received from a web exception, but getting another web exception. Why is the second WebException thrown?

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());
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why is this surprising? Try the following from 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."+
                        "

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...