Frequently Used Status Code And How To Return Them From ASP.NET Core Web API

Request and response are the backbones of any RESTful Web API. Every status code has a specific meaning and during the development, we must make sure that we are returning a valid response with a valid status code.
 

What is the Status Code

 
Status code is a numeric value, and it is the main component of HTTP Response. The status code is issued by the server based on the operation, input data, and some other parameters.
 
The status code gives some useful information about the behavior of the response.
 

Status code categories

 
All status codes are divided into the following 5 categories,
  • 1xx – Informational
  • 2xx – Successful
  • 3xx – Redirection
  • 4xx – Client Error
  • 5xx – Server Error
Asp.Net Core Web API has some built-in methods to return the proper status code.
 

Setup the project

 
Let us create a new Asp.Net Core Web API application. Now in this application let's add a new class Employee.cs under the Model folder.
  1. public class Employee  
  2. {  
  3.     public int Id { getset; }  
  4.     public string Name { getset; }  
  5.     public string Email { getset; }  
  6. }  
We also need to add a new controller with name EmployeesController at the Controllers folder.
  1. [Route("api/[controller]")]  
  2. [ApiController]  
  3. public class EmployeesController : ControllerBase  
  4. {  
  5.         
  6. }  
Time to create some hard-coded, in-memory data for employees. because we are only learning about the status code and how to return them from asp.net core web api so hard code data will work for the demo app. In a real application, you will get the data from a database.
 
For this, we will create a new private method in the EmployeesController.
  1. private List<Employee> EmployeeData()  
  2. {  
  3.     return new List<Employee>()  
  4.     {  
  5.         new Employee(){ Id=1, Name = "Employee 1", Email = "employee1@nitishkaushik.com"},  
  6.         new Employee(){ Id=2, Name = "Employee 2", Email = "employee2@nitishkaushik.com"},  
  7.         new Employee(){ Id=3, Name = "Employee 3", Email = "employee3@nitishkaushik.com"},  
  8.         new Employee(){ Id=4, Name = "Employee 4", Email = "employee4@nitishkaushik.com"},  
  9.         new Employee(){ Id=5, Name = "Employee 5", Email = "employee5@nitishkaushik.com"}  
  10.     };  
  11. }  
Let us learn about the status code and how to return them from Asp.Net Core Web API,
 

200 status code

 
This is the most common status code that is returned from Web API.
 
This 200 status code belongs to the Successful category. It means everything about the operation is successful.
 
Example
  • Get all employees data
  • Get single employee data 
Asp.Net Core has Ok() method to return 200 status code.
  1. public IActionResult GetEmployees()  
  2. {  
  3.     return Ok();  
  4. }  
 This Ok() method can have none or object parameters. 
  1. public IActionResult GetEmployees()  
  2. {  
  3.     var employees = EmployeeData();  
  4.     return Ok(employees);  
  5. }  

201 Status code

 
201 status code indicates that the new resource has been created successfully and the server will return the link to get that newly created resource.
 
 In Asp.Net Core we can use the following methods to return the 201 status code.
  • Created
  • CreatedAtAction
  • CreatedAtRoute
All these methods need the URL to get the newly created resource.
 
Created 
  1. [HttpPost("")]  
  2. public IActionResult AddEmployee([FromBody] Employee model)  
  3. {  
  4.     // code to add new employee here  
  5.     // int id = call to service.  
  6.     return Created("~api/employees/1", model);  
  7. }  
CreatedAtAction
  1. [HttpGet("{id}")]  
  2. public IActionResult GetEmployeeById([FromRoute] int id)  
  3. {  
  4.     var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();  
  5.     return Ok(employee);  
  6. }  
  7.   
  8. [HttpPost("")]  
  9. public IActionResult AddEmployee([FromBody] Employee model)  
  10. {  
  11.     // code to add new employee here  
  12.     int newEmployeeId = 1; // get this id from database.  
  13.     return CreatedAtAction("GetEmployeeById"new { id = newEmployeeId }, model);  
  14. }   
CreatedAtRoute
  1. [HttpGet]    
  2. [Route("{id}", Name = "getEmployeeRoute")]    
  3. public IActionResult GetEmployeeById([FromRoute] int id)    
  4. {    
  5.     var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();    
  6.     return Ok(employee);    
  7. }    
  8.     
  9. [HttpPost("")]    
  10. public IActionResult AddEmployee([FromBody] Employee model)    
  11. {    
  12.     // code to add new employee here    
  13.     int newEmployeeId = 1; // get this id from database.    
  14.     return CreatedAtRoute("getEmployeeRoute"new { id = newEmployeeId }, model);    
  15. }    
This method will add a new response header with a key Location and a URL in the value to get this resource.
 

202 status code

 
202 status indicates that the request has been accepted but the processing is not yet complete.
 
In Asp.Net Core we can use the following methods to return the 202 status code.
  • Accepted
  • AcceptedAtAction
  • AcceptedAtRoute
  1. [HttpPost("")]  
  2. public IActionResult AddEmployee([FromBody] Employee model)  
  3. {  
  4.     // code goes here  
  5.     return Accepted();  
  6. }  

400 status code

 
400 status code indicated the bad request. It means there is something wrong in the request data.
 
In asp.net core we can return 400 status using the BadRequest method. 
  1. [HttpPost("")]  
  2. public IActionResult AddEmployee([FromBody] Employee model)  
  3. {  
  4.     // code goes here  
  5.     return BadRequest();  // returns 400 status code  
  6. }  

404 status code

 
If we are looking for a resource that does not exist, then the server returns a 404 status code.
 
In asp.net core we can return 404 status using the NotFound() method.
  1. [HttpGet]  
  2. [Route("{id}", Name = "getEmployeeRoute")]  
  3. public IActionResult GetEmployeeById([FromRoute] int id)  
  4. {  
  5.     var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();  
  6.     if (employee == null)  
  7.     {  
  8.         return NotFound();  
  9.     }  
  10.     return Ok(employee);  
  11. }  

301 & 302 Status code

 
301 & 302 are used for local redirection. It means if you are trying to access an action method and from that action method you are redirecting the call to some other action method within the same application then in the response of this request there will be a 301 or 302 status code and a new response header with name Location.
 
The client will send another request on the value given in the Location header.
 
In case you are redirecting temporary then the status code will be 302. Or if you are redirecting permanently then the status code will be 301. 
 
In asp.net core we can return 302 status using the LocalRedirect() method.
  1. [HttpGet]  
  2. [Route("{id}", Name = "getEmployeeRoute")]  
  3. public IActionResult GetEmployeeById([FromRoute] int id)  
  4. {  
  5.         return LocalRedirect("~/api/employees");  
  6. }   
In asp.net core we can return 302 status using the LocalRedirectPermanent() method.
  1. [HttpGet]  
  2. [Route("{id}", Name = "getEmployeeRoute")]  
  3. public IActionResult GetEmployeeById([FromRoute] int id)  
  4. {  
  5.         return LocalRedirectPermanent("~/api/employees");  
  6. }  
Other than this there are lots more built-in methods to return different status codes.
 
Click below  to learn more about Asp.Net Core Web API,