我发现了一个异常,我已经通过两种方式完成了。使用第一种方法,我正在捕获完整的异常,检查内部异常是否为 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
}
}
任何想法为什么我能够解析第二个示例中的响应但不能解析第一个示例中的响应?