ASP.NET Get Web Response when HTTP Status is NOT 200 OK

18,866
var request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com/1");
try
{
    using (WebResponse response = request.GetResponse())
    {
        // Success
    }
}
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse)response;
        Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
        using (var streamReader = new StreamReader(response.GetResponseStream()))
            Console.WriteLine(streamReader.ReadToEnd());
    }
}
Share:
18,866
Steve Kiss
Author by

Steve Kiss

Updated on June 20, 2022

Comments

  • Steve Kiss
    Steve Kiss almost 2 years

    I need to read the response from an HTTP GET in situations where the Response Status code is not 200 OK. Sometimes it is 401, other 403, however there will be a Response content. If I try to use the HttpWebResponse and HttpWebRequest classes, it throws an exception when the response status is not 200 OK. Any suggestions?