System.Net.WebException HTTP status code

Gilsham picture Gilsham · Sep 1, 2010 · Viewed 108.5k times · Source

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

Answer

LukeH picture LukeH · Sep 1, 2010

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