首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取WebException的响应流时的WebException

读取WebException的响应流时的WebException
EN

Stack Overflow用户
提问于 2009-07-22 20:07:44
回答 1查看 15.2K关注 0票数 14

我正在与来自.Net的web服务器通信。web服务器抛出500内部服务器错误,并写入详细的错误消息。

我正在尝试读取从web异常收到的错误消息,但获得了另一个web异常。为什么抛出第二个WebException?

代码语言:javascript
复制
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());
  }
}
EN

回答 1

Stack Overflow用户

发布于 2009-07-22 20:26:04

这有什么好惊讶的呢?尝试从MSDN执行以下操作:

代码语言:javascript
复制
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);
}
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1167913

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档