1

我发现了一个异常,我已经通过两种方式完成了。使用第一种方法,我正在捕获完整的异常,检查内部异常是否为 WebException 类型,如果是,则获取响应流。下面是第一个示例,但是我总是得到一个零字符串响应:

catch (Exception e)
{
    if (e.InnerException is WebException)
    {
        WebException webEx = (WebException)e.InnerException;
        HttpWebResponse myResponse = webEx.Response as HttpWebResponse;
        string response = string.Empty;

        if (myResponse != null)
        {
            StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            response = strm.ReadToEnd();
            //EMPTY RESPONSE
        }
    }
}

但是,如果我捕捉到 Web 异常,并且几乎做同样的事情,我会得到很好的响应:

catch (WebException e)
{
    HttpWebResponse myResponse = e.Response as HttpWebResponse;
    string response = string.Empty;

    if (myResponse != null)
    {
        StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        response = strm.ReadToEnd();
        //POPULATED RESPONSE
    }
}

任何想法为什么我能够解析第二个示例中的响应但不能解析第一个示例中的响应?

4

2 回答 2

0

不要看 InnerException,在第二个示例中,您正在读取捕获的异常的响应,这就是它起作用的原因。只需将其更改为此,应该可以正常工作:

catch (Exception e)
{
  if (e is WebException)
  {
      WebException webEx = (WebException)e;
      HttpWebResponse myResponse = webEx.Response as HttpWebResponse;
      string response = string.Empty;

      if (myResponse != null)
      {
          StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
          response = strm.ReadToEnd();
      }
  }
}
于 2012-06-04T22:39:20.187 回答
-1

不要检查InnerException,它是Exception导致当前异常的实例(来自 MSDN

只需检查Exception-

        catch (Exception e)
        {
            if (e is WebException)
            {
                WebException webEx = (WebException)e.InnerException;
                HttpWebResponse myResponse = webEx.Response as HttpWebResponse;
                string response = string.Empty;

                if (myResponse != null)
                {
                    StreamReader strm = new  StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                    response = strm.ReadToEnd();
                    //EMPTY RESPONSE
                }
            }
        }

希望能帮助到你 !!

于 2012-10-08T09:43:38.207 回答