Quick Tip – Return HTTP Status Code from ASP.NET Core Methods

It is advisable to return the proper HTTP status code in response to a client request. This helps the client to understand the request’s result and then take corrective measure to handle it. Proper use of the status codes will help to handle a request’s response in an appropriate way. Out of the box, ASP.NET Core has inbuilt methods for the most common status codes. Like,

return Ok(); // Http status code 200

return Created(); // Http status code 201

return NoContent(); // Http status code 204

return BadRequest(); // Http status code 400

return Unauthorized(); // Http status code 401

return Forbid(); // Http status code 403

return NotFound(); // Http status code 404

As per my knowledge, ASP.NET Core doesn’t have inbuilt methods forall the HTTP status codes. Sometimes, you will need to return status codes without such an inbuilt method. Status codes without such a shortcut method can be returned through the StatusCode method which accepts an integer as an input. You can pass the status code number. Like,

Everyone doesn’t have a memory like an elephant. One can’t get the status code description based on the status code number unless a comment is put in the code. Here is a quick tip, ASP.NET Core has a class named StatusCodes, having constant for all HTTP status code. You can use constant fields defined in StatusCodes class. Like,