简体   繁体   English

HttpWebResponse返回404错误

[英]HttpWebResponse returns 404 error

How to let Httpwebresponse ignore the 404 error and continue with it? 如何让Httpwebresponse忽略404错误并继续使用它? It's easier than looking for exceptions in input as it is very rare when this happens. 它比在输入中查找异常更容易,因为在发生这种情况时非常罕见。

I'm assuming you have a line somewhere in your code like: 我假设你的代码中有一行代码如:

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Simply replace it with this: 只需将其替换为:

HttpWebResponse response;

try
{
    response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    response = ex.Response as HttpWebResponse;
}
    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...
        }
    }

If you look at the properties of the WebException that gets thrown, you'll see the property Response . 如果查看抛出的WebException的属性,您将看到属性Response Is this what you are looking for? 这是你想要的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM