views:

27

answers:

1

I’m trying to read the HTTP response code from a remote server but am running into some trouble when it throws an internal server error. In the following code, GetResponse() can throw a WebException when the remote machine returns an error. I’m currently catching the error and assuming it was a HttpStatusCode.InternalServerError but this is often not correct.

var req = (HttpWebRequest)WebRequest.Create(uri);
HttpStatusCode responseCode;
try
{
  using (var resp = (HttpWebResponse)req.GetResponse())
  {
    responseCode = resp.StatusCode;
  }
}
catch (WebException)
{
  responseCode = HttpStatusCode.InternalServerError;
}

So the question is this: regardless of what errors the remote server is throwing, how can I grab just the remote response code? I need to know which error type it is; is there any way to grab this from the HttpWebResponse without trying to hack around it? Thanks!

+1  A: 

Use the web exception which is thrown to get the response, which contains the status code:

catch (WebException e)
{
    HttpWebResponse response = (HttpWebResponse) e.Response;
    responseCode = response.StatusCode;
}

I agree it's a bit annoying. I don't know of a way of telling HttpWebRequest to just give you the response without throwing the exception (leaving it to you to check the status code yourself).

Jon Skeet
Perfect, but what took you so long?! :) I'd gone down this path before but neglected to cast the exception to an HttpWebResponse.
Troy Hunt