读取WebException响应流时出现WebException

14

我正在使用.Net与Web服务器进行通信。Web服务器抛出500内部服务器错误并编写了详细的错误消息。

我试图读取从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());
  }
}
1个回答

13

为什么这个令人惊讶?尝试使用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);
}

因为我想要实际读取通过网络传输的错误消息。该网站并非不存在,它会回复一个错误,我想在客户端记录/分析该错误。 - ripper234
如果网站不存在,错误从哪里来?无论如何,已更新。 - John Saunders
更新仍然没有太大帮助 - 我不明白为什么在catch块中会出现异常。 - ripper234
1
有趣。我错过了“非”字。请在 catch 块中发布完整的异常。发布 ex.ToString() 的结果。另外,如果您实现了上面的代码,((HttpWebResponse)e.Response).StatusCode 和 .StatusDescription 的值是多少? - John Saunders

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接