System.Net.WebException HTTP 状态代码

发布于 2024-09-16 23:30:13 字数 58 浏览 8 评论 0原文

有没有一种简单的方法可以从 System.Net.WebException 获取 HTTP 状态代码?

Is there an easy way to get the HTTP status code from a System.Net.WebException?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小伙你站住 2024-09-23 23:30:14

(我确实意识到这个问题很老了,但它是 Google 上最热门的问题之一。)

您想知道响应代码的常见情况是在异常处理中。从 C#7 开始,您可以使用模式匹配实际上仅在异常与您的谓词匹配时才输入 catch 子句:

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

这可以轻松扩展到更高的级别,例如在 WebException 的情况下实际上是另一个内部异常(我们只对 404 感兴趣):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

最后:请注意,当它与您的条件不匹配时,无需在 catch 子句中重新抛出异常,因为我们在上述解决方案中首先没有输入该子句。

(I do realise the question is old, but it's among the top hits on Google.)

A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

花开浅夏 2024-09-23 23:30:14

仅当 WebResponse 是 HttpWebResponse 时这才有效。

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}
女中豪杰 2024-09-23 23:30:14

您可以尝试使用此代码从 WebException 获取 HTTP 状态代码。它也适用于 Silverlight,因为 SL 没有定义 WebExceptionStatus.ProtocolError。

HttpStatusCode GetHttpStatusCode(WebException we)
{
    if (we.Response is HttpWebResponse)
    {
        HttpWebResponse response = (HttpWebResponse)we.Response;
        return response.StatusCode;
    }
    return null;
}

You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(WebException we)
{
    if (we.Response is HttpWebResponse)
    {
        HttpWebResponse response = (HttpWebResponse)we.Response;
        return response.StatusCode;
    }
    return null;
}
空城缀染半城烟沙 2024-09-23 23:30:14

我不确定是否有,但如果有这样的财产,它就不会被认为是可靠的。 WebException 可能因 HTTP 错误代码以外的原因而被触发,包括简单的网络错误。那些没有这样匹配的http错误代码。

您能否向我们提供更多有关您尝试使用该代码完成的任务的信息。可能有更好的方法来获取您需要的信息。

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

平生欢 2024-09-23 23:30:13

也许是这样的……

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}
少年亿悲伤 2024-09-23 23:30:13

通过使用空条件运算符 (?.)您可以使用一行代码获取 HTTP 状态代码:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

变量 status 将包含 HttpStatusCode。当出现更常见的故障(例如网络错误)且未发送任何 HTTP 状态代码时,status 将为 null。在这种情况下,您可以检查 ex.Status 以获取 WebExceptionStatus

如果您只想在发生故障时记录描述性字符串,可以使用 null -coalescing 运算符 (??) 来获取相关错误:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

如果由于 404 HTTP 状态代码而引发异常,则字符串将包含“NotFound”。另一方面,如果服务器离线,则字符串将包含“ConnectFailure”等。

(对于任何想知道如何获取 HTTP 子状态的人
代码。那是不可能的。这是一个 Microsoft IIS 概念,仅
登录服务器但从未发送到客户端。)

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus
code. That is not possible. It is a Microsoft IIS concept that is only
logged on the server and never sent to the client.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文