Skip to main content

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 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);
}

Return HTTP Status Codes from ASP.NET Core Methods

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.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

One thought to “Quick Tip – Return HTTP Status Code from ASP.NET Core Methods”

Leave a Reply

Your email address will not be published. Required fields are marked *