繁体   English   中英

System.Net.WebException HTTP状态代码

[英]System.Net.WebException HTTP status code

是否有一种从System.Net.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
    }
}

通过使用空条件运算符?. ),您可以使用一行代码获取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概念,只记录在服务器上,永远不会发送到客户端。)

这仅适用于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子句与你的标准不匹配时,如何不需要在catch子句中重新抛出异常,因为我们不会在上面的解决方案中首先输入该子句。

您可以尝试使用此代码从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错误代码(包括简单的网络错误)以外的原因,可能会触发WebException 那些没有匹配的http错误代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM