.net - 如何停止 .Net HttpWebRequest.GetResponse() 引发异常

标签 .net asp.net exception httpwebrequest

当然,当然,肯定有一种方法可以配置 .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/

相关文章:

c# - PathTooLongException C# 4.5

c# - 从大字符串 C# 中提取子字符串?

c# - 虚拟泛型方法调用是如何实现的?

c# - 从 C# 调用 C++ 函数 - 结构体、指针、函数指针

c# - 如何在Key Container中存储私钥?

asp.net - 为什么我不能结合 if 和 eval?什么是最好的选择?

python - 为什么 Python 带有参数的 raise 需要解包?

c# - 从 C# Code-Behind 触发的 SQL 存储过程不适用于 UPDATE

asp.net - 未处理的 IIS 异常 - 我如何追踪它

c# - WinForms:驱动器中没有磁盘。请将磁盘插入驱动器