How can I get Http Status Code?

J

Jon Maz

Hi All,

Here's the code:

HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.asdfasdfasdfafsd.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Response.Write(HttpWResp.StatusCode);

Here's what I would like it to return to me:
HTTP/1.1 400 Bad Request

And here's what it actually gives me:
The underlying connection was closed: The remote name could not be
resolved.

Any ideas how I can get the 400 code returned?

Thanks,


JON
 
J

Jon Skeet [C# MVP]

Jon Maz said:
Here's the code:

HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.asdfasdfasdfafsd.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Response.Write(HttpWResp.StatusCode);

Here's what I would like it to return to me:
HTTP/1.1 400 Bad Request

And here's what it actually gives me:
The underlying connection was closed: The remote name could not be
resolved.

Any ideas how I can get the 400 code returned?

Hang on a sec - does www.asdfasdfasdfafsd.com exist and return that
response, or does it genuinely not exist? If it's the latter, there
*is* no 400 code to be returned - it couldn't even send the request, so
it can't get back a response code.
 
J

Jerry III

Yeah but you can't get a response from a server that doesn't exist (or one
you can't connect to) - which is the problem here (the name cannot be
resolved)... It's just not going to happen. You need to catch the exception.

Jerry
 
J

Jon Maz

Exactly right - but the StatusCode property is in the HttpWebResponse, not
in the Exception!

Any ideas?

JON
 
J

Jon Skeet [C# MVP]

Jon Maz said:
Exactly right - but the StatusCode property is in the HttpWebResponse, not
in the Exception!

Any ideas?

The WebException will contain a WebResponse.
 
J

Jon Maz

But WebException.Response is of type WebResponse, which doesn't have a
StatusCode property (only HttpResponse or HttpWebResponse do).

I did just try casting it into an HttpWebResponse and getting the StatusCode
that way, but it didn't work.

Cheers,

JON
 
J

Jon Maz

Actually although the documentation it says it's of type WebResponse, and
the IDE reacts as if it is a WebResponse, it actually seems to *be* an
HttpWebResponse.

More importantly, I have now got it working - thanks for the help!

JON
 
J

Jon Skeet [C# MVP]

Jon Maz said:
Actually although the documentation it says it's of type WebResponse, and
the IDE reacts as if it is a WebResponse, it actually seems to *be* an
HttpWebResponse.

Yes - and that makes perfect sense, as an HttpWebResponse *is* a
WebResponse.
More importantly, I have now got it working - thanks for the help!

Goodo.
 

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