C# 为什么 HttpWebRequest 抛出异常而不是返回 HttpStatusCode.NotFound?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10081726/
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-09 12:23:00  来源:igfitidea点击:

Why does HttpWebRequest throw an exception instead returning HttpStatusCode.NotFound?

c#asp.nethttpwebrequesthttp-status-code-404

提问by SelAromDotNet

I'm trying to verify the existence of a Url using HttpWebRequest. I found a few examples that do basically this:

我正在尝试使用 HttpWebRequest 验证 Url 的存在。我发现了一些基本上可以做到这一点的例子:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    return response.StatusCode;
}

However, if the url is indeed broken, it's not returning a response, it's instead throwing an exception.

但是,如果 url 确实损坏了,它不会返回响应,而是抛出异常。

I modified my code to this:

我将代码修改为:

try
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
    request.Method = "HEAD";
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        return response.StatusCode;
    }
}
catch (System.Net.WebException ex)
{
    var response = ex.Response as HttpWebResponse;
    return response == null ? HttpStatusCode.InternalServerError : response.StatusCode;
}

which seems to finally do what I want.

这似乎终于做我想做的。

But I would like to know, why is the request throwing an exception instead of returning the response with a NotFound status code?

但是我想知道,为什么请求会抛出异常而不是返回带有 NotFound 状态代码的响应?

采纳答案by Will

Ya this can be quite annoying when web pages use status codes heavily and not all of them are errors. Which can make processing the body quite a pain. Personally I use this extension method for getting the response.

是的,当网页大量使用状态代码并且并非所有状态代码都是错误时,这可能会很烦人。这可以使处理身体相当痛苦。我个人使用此扩展方法来获取响应。

public static class HttpWebResponseExt
{
    public static HttpWebResponse GetResponseNoException(this HttpWebRequest req)
    {
        try
        {
            return (HttpWebResponse)req.GetResponse();
        }
        catch (WebException we)
        {
            var resp = we.Response as HttpWebResponse;
            if (resp == null)
                throw;
            return resp;
        }
    }
}

回答by Mahmoud Al-Qudsi

Why not? They're both valid design options, and HttpWebRequest was just designed to work this way.

为什么不?它们都是有效的设计选项,而 HttpWebRequest 就是为了以这种方式工作而设计的。