• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

question with C# Request.GetResponse function

fishjie

Senior member
Ok in my code I create an HttpRequest object. I then use the Request.GetResponse() to get a response. Now sometimes the response does not return a status code of 200, and this causes an exception to be thrown. I would like to be able to get the status code and status description members of the response object, however, it looks like the response object is NULL.

I dont understand why microsoft decided to throw an exception and keep response NULL, instead of allowing us to see what the status code and status description were. What can I do to get around this? I know I can parse out the status code in the exception message, but I can't do this with the status description (Microsoft reports the default status description associated with the status code; however there are custom status descriptions used here that I want to parse). Here is my code:

WebResponse response;
try
{
response = request.GetResponse();
//process the response.........
}
catch(Exception e)
{
//here i would like to get response.StatusCode
//and response.StatusDescription
//however response is NULL at this point
}
 
It will throw a WebException which includes the HTTP response as a member variable:

http://msdn2.microsoft.com/en-....net.webexception.aspx

try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");

// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
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);
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
 
Back
Top