C# - 无法从内部异常获取WebException响应

时间:2012-06-04 20:37:38

标签: c# web-services exception exception-handling

我正在捕捉一个异常,我已经用两种方式完成了。使用第一种方法,我正在捕获完整的异常,检查内部异常是否为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
    }
}

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

2 个答案:

答案 0 :(得分: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();
      }
  }
}

答案 1 :(得分:-1)

请勿检查InnerExceptionException实例导致当前异常(From 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
                }
            }
        }

希望它有所帮助!!