System.Net.WebException HTTP status code

前端 未结 6 1902
执笔经年
执笔经年 2020-12-02 11:27

Is there an easy way to get the HTTP status code from a System.Net.WebException?

6条回答
  •  难免孤独
    2020-12-02 12:13

    (I do realise the question is old, but it's among the top hits on Google.)

    A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

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

    This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

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

    Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

提交回复
热议问题