System.Net. WebException HTTP状态码

有没有一种简单的方法可以获得 HTTP状态码?

134694 次浏览

我不知道是否有,但如果有这样的财产,它不会被认为是可靠的。由于 HTTP 错误代码以外的原因(包括简单的网络错误) ,可以触发 WebException。它们没有这种匹配的 http 错误代码。

你能给我们一些更多的信息,关于你试图完成的代码。也许有更好的方法来获得你需要的信息。

也许像这样的事..。

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

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

你可以尝试这段代码从 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;
}

通过使用 空条件运算符(?.) ,你只需要一行代码就可以得到 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”。另一方面,如果服务器脱机,字符串将包含“ Connectfalse”等等。

(对于任何想知道如何获得 HTTP 子状态的人来说 这是不可能的。这是一个微软 IIS 的概念,只有 登录到服务器上,但从未发送到客户端。)

(我的确意识到这个问题有些老套,但它在谷歌(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 子句不符合您的条件时,没有必要重新抛出该异常,因为我们首先没有使用上述解决方案输入该子句。