System.Net.WebException HTTP状态码

有没有一种简单的方法从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; 

variablesstatus将包含HttpStatusCode 。 当有一个更为普遍的故障,如没有发送HTTP状态码的networking错误时, status将为空。 在这种情况下,您可以检查ex.Status以获取WebExceptionStatus

如果你只是想要一个描述性的string来logging失败的情况下,你可以使用空合并运算符 ( ?? )来获得相关的错误:

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

如果由于404 HTTP状态码引发exception,则string将包含“NotFound”。 另一方面,如果服务器处于脱机状态,string将包含“ConnectFailure”等。

(对于任何想知道如何获得HTTP子代码的人来说,这是不可能的,这是一个微软IIS的概念,只logging在服务器上,从来没有发送给客户端。)

这仅适用于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; } 

我不确定是否有这样的财产,但不会被认为是可靠的。 由于HTTP错误代码(包括简单的networking错误)以外的原因,可能会触发WebException 。 那些没有这样匹配的http错误代码。

你可以给我们多一点你想用这个代码来完成的信息。 可能有更好的方法来获取您所需要的信息。

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

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

(我确实意识到这个问题已经很老了,但是它在Google上是最受欢迎的。)

您想知道响应代码的常见情况是在exception处理中。 从C#7开始,如果exception与谓词相匹配,则可以使用模式匹配实际上仅inputcatch子句:

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

这可以很容易地扩展到更高层次,比如在这种情况下, WebException实际上是另一个的内部exception(我们只对404感兴趣):

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

最后:注意,如果catch子句中的exception不符合条件,那么不需要重新抛出exception,因为我们并没有在上面的解决scheme中首先input子句。