Skip to main content

How to Check an HTTP Status Code with the HttpStatusCode Enum in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

An HTTP status code is a number, such as 404, and the HttpStatusCode enum gives each one a name, such as NotFound. Cast a number to HttpStatusCode to get its name, compare with names instead of numbers, and cast back to int when you need the number.

HttpStatusCode is an enum in the System.Net namespace. Microsoft's API reference describes it as: Contains the values of HTTP status codes as defined by RFC 9110, section 15. Each of its members is a name for one of those numbers.

Because it's an enum, a number and its name convert into each other with a cast. The C# reference: For any enumeration type, explicit conversions exist between the enumeration type and its underlying integral type.

Syntax​

Syntax
using System.Net;

HttpStatusCode <status> = (HttpStatusCode)<number>;
bool <isMatch> = <status> == HttpStatusCode.<Name>;
int <code> = (int)HttpStatusCode.<Name>;
PartWhat it is
using System.Net;Lets you write HttpStatusCode by its short name. A console app doesn't include this namespace by itself
(HttpStatusCode)<number>A cast that turns a status code number into an HttpStatusCode
<number>An int that holds a status code, such as 404
<status>The status as an HttpStatusCode. Printed, it shows its name, such as NotFound
HttpStatusCode.<Name>One of the enum's names, such as NotFound, Conflict or PreconditionFailed
<status> == HttpStatusCode.<Name>Compares the status with a name. It's true when both stand for the same number
(int)HttpStatusCode.<Name>A cast back to int, which gives the name's number
<isMatch>, <code>The results: a bool and an int

The Example​

A console app called HttpStatusCodeEnum starts with four status codes as plain numbers, the way a web server sends them: 200, 404, 409 and 412. It turns each one into an HttpStatusCode and prints its name. Then it checks a 404 against HttpStatusCode.NotFound, and turns PreconditionFailed back into its number. It sends no web request: the numbers are written in the code.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n HttpStatusCodeEnum
cd HttpStatusCodeEnum
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/HttpStatusCodeEnum/HttpStatusCodeEnum.csproj:
Determining projects to restore...
Restored /Users/you/source/HttpStatusCodeEnum/HttpStatusCodeEnum.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n HttpStatusCodeEnum creates a folder named HttpStatusCodeEnum with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or HttpStatusCodeEnum.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the using directive and the numbers:

Program.cs (the numbers)
using System.Net;

// Status codes as a web server sends them: plain numbers.
int[] codes = [200, 404, 409, 412];

HttpStatusCode is in the System.Net namespace. A console app's implicit using directives include System.Net.Http, but not System.Net, and Microsoft's guide says: If you need using directives that aren't implicitly included, add them to the .cs file that contains top-level statements or to other .cs files. codes holds the four status codes as int values.

Then each number's name:

Program.cs (number to name)
foreach (int code in codes)
{
// A cast turns the number into an HttpStatusCode, which prints as its name.
HttpStatusCode status = (HttpStatusCode)code;
Console.WriteLine($"{code} is {status}");
}

(HttpStatusCode)code is a cast from int to HttpStatusCode. Printed, an HttpStatusCode shows its name. The Enum.ToString reference says that when there is a named constant equal to the value of this instance, then the return value is a string containing the name of the constant.

Then a check with a name:

Program.cs (compare with a name)
// Compare with a name: HttpStatusCode.NotFound says more than 404.
HttpStatusCode reply = (HttpStatusCode)404;
if (reply == HttpStatusCode.NotFound)
Console.WriteLine("The page isn't there");

reply == HttpStatusCode.NotFound compares two HttpStatusCode values, and it's true when both stand for the same number. The name also tells the reader what the code means. The API reference describes NotFound as: Equivalent to HTTP status 404. NotFound indicates that the requested resource does not exist on the server.

Last, a name back to its number:

Program.cs (name to number)
// A cast to int turns a name back into its number.
Console.WriteLine($"PreconditionFailed is {(int)HttpStatusCode.PreconditionFailed}");

(int)HttpStatusCode.PreconditionFailed casts the other way, from the name to an int. The C# reference: If you cast an enum value to its underlying type, the result is the associated integral value of an enum member.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
200 is OK
404 is NotFound
409 is Conflict
412 is PreconditionFailed
The page isn't there
PreconditionFailed is 412

macOS-style terminal window titled Terminal — HttpStatusCodeEnum showing dotnet run printing 200 is OK, 404 is NotFound, 409 is Conflict and 412 is PreconditionFailed, then The page isn't there, then PreconditionFailed is 412

Each number printed its name: 200 is OK, 404 is NotFound, 409 is Conflict and 412 is PreconditionFailed. reply was 404, so the comparison with HttpStatusCode.NotFound was true and printed The page isn't there. The cast back to int printed 412.

The Complete File​

macOS-style code window titled Program.cs — HttpStatusCodeEnum showing using System.Net, an array of four status code numbers that are cast to HttpStatusCode and printed, a comparison with HttpStatusCode.NotFound, and a cast of HttpStatusCode.PreconditionFailed back to int

Program.cs
using System.Net;

// Status codes as a web server sends them: plain numbers.
int[] codes = [200, 404, 409, 412];

foreach (int code in codes)
{
// A cast turns the number into an HttpStatusCode, which prints as its name.
HttpStatusCode status = (HttpStatusCode)code;
Console.WriteLine($"{code} is {status}");
}

// Compare with a name: HttpStatusCode.NotFound says more than 404.
HttpStatusCode reply = (HttpStatusCode)404;
if (reply == HttpStatusCode.NotFound)
Console.WriteLine("The page isn't there");

// A cast to int turns a name back into its number.
Console.WriteLine($"PreconditionFailed is {(int)HttpStatusCode.PreconditionFailed}");

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out using System.Net;The build stopped with error CS0246: The type or namespace name 'HttpStatusCode' could not be found (are you missing a using directive or an assembly reference?), twiceAdd using System.Net; at the top of Program.cs
Treating only OK as a successstatus == HttpStatusCode.OK was False for 201 Created and 204 NoContent, which Microsoft's HttpClient guide lists among the other HTTP status codes that represent a successful responseCheck the range: (int)status is >= 200 and <= 299 was True for 200, 201 and 204, and False for 404. A response's IsSuccessStatusCode gave the same four answers
Expecting the cast to reject a number with no name(HttpStatusCode)499 built and ran, and printed 499. The C# guide: Be aware that casting an integer to an enum doesn't validate whether the value matches a defined member.Check it with Enum.IsDefined(status), which printed False for 499

FAQ​

What do Conflict and PreconditionFailed mean?​

The API reference describes each name. Conflict: Equivalent to HTTP status 409. Conflict indicates that the request could not be carried out because of a conflict on the server. PreconditionFailed: Equivalent to HTTP status 412. PreconditionFailed indicates that a condition set for this request failed, and the request cannot be carried out. Conditions are set with conditional request headers like If-Match, If-None-Match, or If-Unmodified-Since.

Why does 302 print Found and not Redirect?​

Because 302 has two names. The API reference: Found is a synonym for Redirect. (HttpStatusCode)302 printed Found, HttpStatusCode.Found == HttpStatusCode.Redirect printed True, and the enum's names for 302 were Found and Redirect. Don't rely on which name prints. The Enum.ToString reference: If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return. Compare values with ==, not the printed names.

Conclusion​

HttpStatusCode gives HTTP status codes names. Add using System.Net;, cast a number with (HttpStatusCode) to get its name, compare with names such as HttpStatusCode.NotFound, and cast with (int) to get the number back. A cast doesn't check the number, so use Enum.IsDefined when it comes from outside your code, and treat every code from 200 to 299 as a success.

Additional Resources​