System.Net.WebException HTTP status code

前端 未结 6 1899
执笔经年
执笔经年 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:23

    this works only if WebResponse is a 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;
    }
    

提交回复
热议问题