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

有帮助吗?

解决方案

也许这样的事情...

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

其他提示

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

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

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

如果您只想在发生故障时记录一个描述性字符串,您可以使用 空合并运算符 (??)得到相关的错误:

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

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

(对于任何想知道如何获取HTTP替代代码的人。这是不可能的。这是Microsoft IIS概念,仅在服务器上登录而从未发送给客户端。)

这只有当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;
}

(我不知道这个问题是旧的,但它是在谷歌排名靠前之中。)

要知道响应代码是异常处理的一种常见情况。由于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子句中的例外,当它不符合你的标准,因为我们不符合上述溶液首位进入该条款

您可以试试这个代码从引发WebException GET HTTP状态代码。它的工作原理在Silverlight也因为SL没有WebExceptionStatus.ProtocolError定义。

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

我不知道是否有,但如果有这样的属性不会被认为是可靠的。一个WebException可以比的原因HTTP其他错误代码,包括简单的网络错误被解雇。那些没有这样的匹配HTTP错误代码。

你能不能给我们你想用代码实现什么更多的信息。有可能是一个更好的方式来获得您所需要的信息。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top