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.
- public class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Email { get; set; }
- }
We also need to add a new controller with name EmployeesController at the Controllers folder.
- [Route("api/[controller]")]
- [ApiController]
- public class EmployeesController : ControllerBase
- {
-
- }
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.
- private List<Employee> EmployeeData()
- {
- return new List<Employee>()
- {
- new Employee(){ Id=1, Name = "Employee 1", Email = "[email protected]"},
- new Employee(){ Id=2, Name = "Employee 2", Email = "[email protected]"},
- new Employee(){ Id=3, Name = "Employee 3", Email = "[email protected]"},
- new Employee(){ Id=4, Name = "Employee 4", Email = "[email protected]"},
- new Employee(){ Id=5, Name = "Employee 5", Email = "[email protected]"}
- };
- }
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.
- public IActionResult GetEmployees()
- {
- return Ok();
- }
This Ok() method can have none or object parameters.
- public IActionResult GetEmployees()
- {
- var employees = EmployeeData();
- return Ok(employees);
- }
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
- [HttpPost("")]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
-
-
- return Created("~api/employees/1", model);
- }
CreatedAtAction
- [HttpGet("{id}")]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();
- return Ok(employee);
- }
-
- [HttpPost("")]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
-
- int newEmployeeId = 1;
- return CreatedAtAction("GetEmployeeById", new { id = newEmployeeId }, model);
- }
CreatedAtRoute
- [HttpGet]
- [Route("{id}", Name = "getEmployeeRoute")]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();
- return Ok(employee);
- }
-
- [HttpPost("")]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
-
- int newEmployeeId = 1;
- return CreatedAtRoute("getEmployeeRoute", new { id = newEmployeeId }, model);
- }
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
- [HttpPost("")]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
-
- return Accepted();
- }
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.
- [HttpPost("")]
- public IActionResult AddEmployee([FromBody] Employee model)
- {
-
- return BadRequest();
- }
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.
- [HttpGet]
- [Route("{id}", Name = "getEmployeeRoute")]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- var employee = EmployeeData().Where(x => x.Id == id).FirstOrDefault();
- if (employee == null)
- {
- return NotFound();
- }
- return Ok(employee);
- }
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.
- [HttpGet]
- [Route("{id}", Name = "getEmployeeRoute")]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- return LocalRedirect("~/api/employees");
- }
In asp.net core we can return 302 status using the LocalRedirectPermanent() method.
- [HttpGet]
- [Route("{id}", Name = "getEmployeeRoute")]
- public IActionResult GetEmployeeById([FromRoute] int id)
- {
- return LocalRedirectPermanent("~/api/employees");
- }
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,