C# HttpWebResponse 返回 404 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1857512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:26:01  来源:igfitidea点击:

HttpWebResponse returns 404 error

c#http-status-code-404httpwebresponse

提问by Skuta

How to let Httpwebresponse ignore the 404 error and continue with it? It's easier than looking for exceptions in input as it is very rare when this happens.

如何让 Httpwebresponse 忽略 404 错误并继续它?这比在输入中查找异常更容易,因为这种情况发生时非常罕见。

采纳答案by Adam Maras

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;
}

回答by spender

If you look at the properties of the WebException that gets thrown, you'll see the property Response. Is this what you are looking for?

如果您查看抛出的 WebException 的属性,您将看到属性Response。这是你想要的?

回答by Phaedrus

    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...
        }
    }