当然,当然,肯定有一种方法可以配置 .Net HttpWebRequest 对象,以便在调用 HttpWebRequest.GetResponse() 并返回任何 300 或 400 状态代码时它不会引发异常?
乔恩·斯基特 does not think so ,所以我几乎不敢问,但我很难相信没有办法解决这个问题。在某些情况下,300 和 400 响应代码是有效的响应。为什么我们总是被迫承担异常的开销?
也许有一些模糊的配置设置避开了 Jon Skeet?也许有一种完全不同类型的请求对象可以使用,它没有这种行为?
(是的,我知道您可以捕获异常并从中获得响应,但我想找到一种不必这样做的方法)。
谢谢你的帮助
最佳答案
如果要从 4xx 错误中检索错误响应,可以这样做:
HttpWebResponse res = null;
string response = string.Empty;
StreamReader sr = null;
Stream resst = null;
try
{
res = (HttpWebResponse)req.GetResponse();
resst = res.GetResponseStream();
sr = new StreamReader(resst);
response = sr.ReadToEnd();
}
catch (WebException exception)
{
HttpWebResponse errorResponse = (HttpWebResponse)exception.Response;
resst = errorResponse.GetResponseStream();
sr = new StreamReader(resst);
response = sr.ReadToEnd();
}
this.Response.Write(response);
希望这可以帮助...
关于.net - 如何停止 .Net HttpWebRequest.GetResponse() 引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2702090/