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!
Use the web exception which is thrown to get the response, which contains the status code:
I agree it’s a bit annoying. I don’t know of a way of telling
HttpWebRequestto just give you the response without throwing the exception (leaving it to you to check the status code yourself).