有没有一种简单的方法可以从 a 获取 HTTP 状态代码System.Net.WebException
?
6 回答
也许像这样的东西......
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
.
如果您只想在发生故障时记录一个描述性字符串,您可以使用null-coalescing 运算符( ??
) 来获取相关错误:
string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
?? ex.Status.ToString();
如果由于 404 HTTP 状态代码而引发异常,则字符串将包含“NotFound”。另一方面,如果服务器离线,则字符串将包含“ConnectFailure”等。
(对于任何想知道如何获取 HTTP 子状态代码的人来说。这是不可能的。这是一个 Microsoft IIS 概念,它只登录到服务器上,从不发送到客户端。)
(我确实意识到这个问题很老了,但它是谷歌的热门话题之一。)
您想知道响应代码的常见情况是异常处理。从 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 子句不符合您的条件时,无需重新抛出异常,因为我们没有在上述解决方案中首先输入该子句。
这仅在 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;
}
我不确定是否有,但如果有这样的财产,它就不会被认为是可靠的。AWebException
可以因为 HTTP 错误代码以外的原因(包括简单的网络错误)而被触发。那些没有这样匹配的http错误代码。
您能否向我们提供有关您尝试使用该代码完成的工作的更多信息。可能有更好的方法来获取您需要的信息。