如何让Httpwebresponse忽略404错误并继续使用它?它比在输入中查找异常更容易,因为在发生这种情况时非常罕见。
答案 0 :(得分:29)
我假设你的代码中某处有一行:
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
只需将其替换为:
HttpWebResponse response;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
答案 1 :(得分:10)
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mysite.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch(WebException ex)
{
HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
//Handle 404 Error...
}
}
答案 2 :(得分:0)
如果查看被抛出的WebException的属性,您将看到属性Response。这是你在找什么?