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.
You're looking for the WebException.Response
property:
catch(WebException ex)
{
var response = (HttpWebResponse)ex.Response;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With