331

I am trying to get the HTTP status code number from the HttpWebResponse object returned from a HttpWebRequest. I was hoping to get the actual numbers (200, 301,302, 404, etc.) rather than the text description. ("Ok", "MovedPermanently", etc.) Is the number buried in a property somewhere in the response object? Any ideas other than creating a big switch function? Thanks.

HttpWebRequest webRequest = (HttpWebRequest)WebRequest
                                           .Create("http://www.gooogle.com/");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
//Returns "MovedPermanently", not 301 which is what I want.
Console.Write(response.StatusCode.ToString());
SteveC
  • 15,808
  • 23
  • 102
  • 173
James Lawruk
  • 30,112
  • 19
  • 130
  • 137

6 Answers6

457
Console.Write((int)response.StatusCode);

HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    but in case of "connectfailure" exception of webexception i get response as null, in that case how can i get the httpstatus code – Rusty Mar 20 '14 at 10:33
  • 10
    @rusty: If the connection failed and thus the request could not be sent and no response could be received, there won't be any http status code. – Oliver Apr 10 '14 at 11:34
  • 4
    How get **HTTP Substatus** value ? For example, _404.13 Content Length Too Large_ Reference: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits – Kiquenet Apr 14 '15 at 08:57
  • 13
    Bonus: `bool success = ((int)response.StatusCode) >= 200 && ((int)response.StatusCode) < 300;` – Alain Aug 04 '15 at 23:22
  • 15
    @Alain Double bonus; bool success = response.IsSuccessStatusCode; – htxryan Sep 18 '16 at 15:03
  • work in asp.net core: with big "R" >> @Response.StatusCode – مهدی Jun 17 '22 at 08:49
  • Reason: response.ReasonPhrase – Ricko.. Oct 05 '22 at 09:27
253

You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
zeldi
  • 4,833
  • 3
  • 19
  • 18
  • 1
    I'm glad you mentioned the 4xx and 5xx because I was having issues with a program not acting properly. I should point out though that the current .NET framework will notify you of any uncaught exceptions so this is also a no-brainer. – Joel Trauger Sep 20 '16 at 16:49
  • As a bonus, one used to be able to decorate a method with [DebuggerNonUserCode] and the Debugger would not stop in that method when an exception is thrown. In this manner [poorly designed exceptions](https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/#comment-85105) could be wrapped and ignored. But now a [registry setting is required](https://blogs.msdn.microsoft.com/devops/2016/02/12/using-the-debuggernonusercode-attribute-in-visual-studio-2015) – crokusek Oct 11 '17 at 02:36
26

As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.

This has worked for me:

HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
    response = (HttpWebResponse)we.Response;
}

statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
Wojciech Jakubas
  • 1,499
  • 1
  • 15
  • 22
  • 1
    HttpWebResponse implements IDisposable so dealing with that can be tricky. You can use the following instead which allows you to declare "response" inside a using block: public HttpWebResponse GetSafeResponse(HttpWebRequest request) { try { return (HttpWebResponse)request.GetResponse(); } catch (WebException we) { return (HttpWebResponse)we.Response; } } – DesertFoxAZ May 04 '20 at 19:35
20

Just coerce the StatusCode to int.

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}
Marc
  • 13,011
  • 11
  • 78
  • 98
4
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)
0

Here's how i am handling such a situation.

//string details = ...
//...
catch (WebException ex)
{
    HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
    if (statusCode == HttpStatusCode.Unauthorized)
    {
        Reconnect();
        //...
    }
    else if (statusCode == HttpStatusCode.NotFound)
    {
        FileLogger.AppendToLog("[ERROR] Not Found: " + details);
    }
    else
    {
        FileLogger.AppendToLog("[ERROR] " + ex.Message + ": " + details);
    }
}