GET original error message with HttpWebResponse

J

Jon Maz

Hi All,

I am using a WebRequest & WebResponse to GET the contents of an aspx page as
a string (code below).

It's working fine, except that when the aspx page has an error on it, I want
to know precisely what the error was (ie I want to get the error message
that would be displayed if you were viewing the aspx page in a brower).

Instead I always get this error:
The remote server returned an error: (500) Internal Server Error
pointing to the line:
WebResponse myResponse = myRequest.GetResponse();

Can anyone tell me how I can GET the original error text returned to me?

Thanks,

JON


=====
CODE
=====


// Initialize the WebRequest.
WebRequest myRequest =
WebRequest.Create("http://localhost/PageWithError.aspx");

// Return the response.
WebResponse myResponse = myRequest.GetResponse();

// Convert the GET to a string and display it
StreamReader sr = new
StreamReader(myResponse.GetResponseStream(),System.Text.Encoding.Default);
string sBuffer;
sBuffer = sr.ReadToEnd();
sr.Close();
txtDisplayHtml.Text = sBuffer;
 
J

Joerg Jooss

Jon said:
Hi All,

I am using a WebRequest & WebResponse to GET the contents of an aspx
page as a string (code below).

It's working fine, except that when the aspx page has an error on it,
I want to know precisely what the error was (ie I want to get the
error message that would be displayed if you were viewing the aspx
page in a brower).

Instead I always get this error:
The remote server returned an error: (500) Internal Server Error
pointing to the line:
WebResponse myResponse = myRequest.GetResponse();

Can anyone tell me how I can GET the original error text returned to
me?

You mean the actual error page's content?

If a WebException is thrown because of a protocol error, its Response
property will give you access to actual response received from the web
server. Just make sure you check the Status property accordingly:

try {
// Do WebRequest
}
catch (WebException ex) {
if (ex.Status == WebExceptionStatus.ProtocolError) {
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null) {
// Process response
}
}
}

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top