Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Getting the response body from a 403 error

I'm receiving a 403 error when requesting data from a URL. This is expected and I'm not asking how to correct it.
When pasting this URL directly into my browser, I get a basic string of information describing why permission is denied.
I need to read this basic error message via my C# code, however when the request is made, a System.Net.WebException ("The remote server returned an error: (403) Forbidden.") error is thrown, and the response body is unavailable to me.

Is it possible to simply grab the content of the page without the exception being thrown? The relevant code is pretty much what you'd expect, but here it is anyway.

   HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(sPageURL);

   try
   {
        //The exception is throw at the line below.
        HttpWebResponse response = (HttpWebResponse)(request.GetResponse());

        //Snipped processing of the response.
   }
   catch(Exception ex)
   {
        //Snipped logging.
   }

Any help would be appreciated. Thanks.

like image 430
Ryan McDermott Avatar asked Mar 23 '11 17:03

Ryan McDermott


2 Answers

You're looking for the WebException.Response property:

catch(WebException ex)
{
     var response = (HttpWebResponse)ex.Response;
}
like image 130
SLaks Avatar answered Sep 17 '22 16:09

SLaks


This worked For me..

HttpWebResponse httpResponse;
            try
            {
                httpResponse = (HttpWebResponse)httpReq.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                Console.WriteLine("This program is expected to throw WebException on successful run." +
                                    "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    using (Stream data = e.Response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
like image 27
nikunjM Avatar answered Sep 19 '22 16:09

nikunjM