System.Net.WebException HTTP status code

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

    Maybe something like this...

    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
        }
    }
    

提交回复
热议问题