phenomena
When we encode the implementation request a page, the requested code resembles the following code:
HttpWebRequest req = (HttpWebRequest) webrequest.create (strURL);
Req. useragent = "MSIE6.0";
Req. method = ' Get ';
HttpWebResponse res = (HttpWebResponse) req. GetResponse ();
StreamReader sr = new StreamReader (res. GetResponseStream (), Strencode);
strHTML = Sr. ReadToEnd ();
Sr. Close ();
However, if the page we are requesting is exactly the same as a page with an unusual occurrence, or a non-existent page. The code above will be in the
Req. GetResponse ();
This throws an exception: The remote server returned an error: (500) an internal server error.
We pass the above code, is not the error occurred when the page source code.
Analysis Reason:
(HttpWebResponse) Req. GetResponse (); This line of code does one of the following things:
When the server segment ASP.net program has Exception occurs, the client application accepts an HTTP protocol error. Convert this HTTP protocol error to Status set to WebExceptionStatus.ProtocolError webexception and throw the exception.
solve the problem
So what if we want to get the source code for the server Segment error page when the error occurs?
In fact, very very simple approach, we use the following code regardless of whether the error occurred, you can get the server section of the page source code.
HttpWebResponse Res;
Try
{
res = (HttpWebResponse) req. GetResponse ();
}
catch (WebException ex)
{
res = (HttpWebResponse) ex. Response;
}
StreamReader sr = new StreamReader (res. GetResponseStream (), Strencode);
strHTML = Sr. ReadToEnd ();
When an exception occurs, WebException not only StatusCode the HTTP error code, but also its Response property contains WebResponse sent by the server,
To indicate the actual HTTP error encountered.
The solution to this problem is so simple, but I encountered this problem, through Google, Baidu Search, unexpectedly many people do not know. So organize this blog to help people who are caught up in this problem.
Attached, derived graphs of HttpWebRequest: System.Object
System.MarshalByRefObject
System.Net.WebRequest
System.IO.Packaging.PackWebRequest
System.Net.FileWebRequest
System.Net.FtpWebRequest
System.Net.HttpWebRequest
Reference:
Use WebClient to get the error page.
Http://topic.csdn.net/t/20061030/17/5120137.html