When building a web server in ASP.NET Core, the APIs that deal with status codes are
int based, there are multiple ways to express a status code in your code, in this post I will share my favourite.
// Stop doing this:
context.Response.StatusCode = (int) HttpStatusCode.PreconditionFailed;
This is the enum we've been using in .NET for a while, it's alright and it still makes sense to use when we are dealing with
HttpClient, as it's the type the response type uses there. However, when you read it you may find yourself having to translate it back to the status code number, I find myself forgetting if "Bad Gateway" is 502 or 503 for example.
Finally, when we are dealing with ASP.NET Core, the status code type used is
int, so we find ourselves having to cast between the two types, not ideal.
As ASP.NET Core wants an
int for status code, we could just express the status code as
int literals, however you have the reverse problem as you do with
HttpStatusCode—what was the meaning of that number again?
This is a static class containing
int constants for every status code, what is great about these is that they include both the number and the name of the status code, so we get the best of both worlds. For example:
Microsoft.AspNetCore.Http.StatusCodes above, if we bring it into the namespace with
using Microsoft.AspNetCore.Http, then we end up repeating ourselves when using it, for example
StatusCodes.Status412PreconditionFailed. Since C# 6, we've been able to open static classes, which makes this much nicer!
// Not for me
context.Response.StatusCode = (int) HttpStatusCode.PreconditionFailed; // What number is it?
context.Response.StatusCode = 412; // What meaning is it?
context.Response.StatusCode = StatusCodes.Status412PreconditionFailed; // Too many duplicated words duplicated
// Perfect ♥
using static Microsoft.AspNetCore.Http.StatusCodes;
context.Response.StatusCode = Status412PreconditionFailed;
Bonus: The F# Version
Since F# 4.7, there is a preview feature to open static classes, just like in C#. Here is an example setting the status code using Giraffe:
let someHttpHandler : HttpHandler =
It's a small detail, but I think it helps keep code noise-free and as readable as possible.