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 200return Created();
// Http status code 201return NoContent();
// Http status code 204return BadRequest();
// Http status code 400return Unauthorized();
// Http status code 401return Forbid();
// Http status code 403return NotFound();
// Http status code 404
As per my knowledge, ASP.NET Core doesn’t have inbuilt methods for all 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,
[HttpGet] [Route("AnotherMethod")] public IActionResult AnotherMethod() { return StatusCode(405); }
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,
[HttpGet] [Route("AnotherMethod")] public IActionResult AnotherMethod() { return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status405MethodNotAllowed); }
That’s it. Hope you find this useful.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
One thought to “Quick Tip – Return HTTP Status Code from ASP.NET Core Methods”