HTTP Status Codes in ASP.NET Core

ASP.Net Tutorials
Requests and responses are the backbones of the communication between the client and the server in any RESTful web API and network application. The RESTful API heavily relies on HTTP status codes for its operations. The RESTful API provides feedback to the user by sending HTTP status messages in the body part of the response. This HTTP status code contains information related to the result processed by the server. In today’s ASP.NET programming tutorial, we will examine each of the HTTP status codes and what they mean.

Read: Best Online Courses for .NET Developers

What are the Types of HTTP Status Codes?

Below is a list of the different types and categories of HTTP status codes a web developer might encounter:

  • 1xx: The HTTP status code starting with 1 is informational and gives information on transfer-level communication protocols.
  • 2xx: Status codes starting with 2 represent a good indication of communication. These types of status codes mean the server accepts the client’s request and returns the desired data.
  • 3xx: These status codes indicate the client has not properly sent the request; it requires a few more actions to complete the request.
  • 4xx: The series starting with 4 represents there is some fault with the request on the client side. This might include accessing prohibited resources or a resource that does not exist.
  • 5xx: This series represents server-side problems. The problem caused on the server side is known as an Internal Server Error. These types of errors are caused due to an inappropriate request sent to the server.

We discuss specific HTTP status codes in the next section.

What is a 200 HTTP Status Code?

The 200 HTTP status code is one of the more common error codes returned from the .NET Web API. This error code represents a ‘Successful’ operation. ASP.NET Core uses an Ok() method to return 200 HTTP status codes. Here is a code example showing how developers can use Ok() in an ASP.NET MVC Controller:

public IActionResult GetStockItems()  
{  
    var items = GetAllStockItems();  // Call to DB service
    return Ok(items);  
}

Read: Top 10 Security Testing Tools for Developers

What is the 201 HTTP Status Code?

The 201 HTTP status code indicates that a new resource has been created. The server returns the link of that newly created resource in the response body.

ASP.NET Core has a few methods that return the 201 status code. They are:

  • Created
  • CreatedAtAction
  • CreatedAtRoute

Let’s try an example of how we can generate a response with the Created() method and the code 201, along with the URI (for a newly created resource) in the response body on the creation of a new resource:

[HttpPost("")]  
public IActionResult AddCustomer([FromBody] Customer model)  
{   
    // Code to create a new Customer
    return Created("~api/customers/1", model);  
}

What is the 202 HTTP Status Code?

The 202 HTTP status code is a response that indicates the processing of a request may take longer than usual to get completed. In such scenarios, the client needs to not hang on the server until the whole process is complete. This is the status code that gets returned while the processing is halfway finished, so an approximate time in which the desired outcome is fulfilled is sent in the body of the response back to the client. In ASP.NET Core, the following methods return the 202 status code:

  • Accepted
  • AcceptedAtAction
  • AcceptedAtRoute

The following code example shows the use of the Accepted() method in ASP.NET:

[HttpPost("")]  
public IActionResult AddItem([FromBody] Item model)  
{  
    // do some operations
    return Accepted();  
}

What is the 301 and 302 HTTP Status Code?

The status code series starting with 3xx means the resources that the client is looking for has been moved permanently to another location. The response body contains the new location (Uniform Response Indicator or URI) where the resource can be found.

In such cases, if you are redirecting to a new URI permanently, the server will respond with 301, and, if redirection is temporary, then 302 will be returned.

ASP.NET Core uses the LocalRedirect() method to return 302 status codes, as depicted following in the following code example:

[HttpGet]  
[Route("{id}", Name = "getCustomer")]  
public IActionResult GetCustomerById([FromRoute] int Id)  
{  
        return LocalRedirect("~/api/customers");  
}

Programmers can return status code 302 using the LocalRedirectPermanent() method:

[HttpGet]  
[Route("{id}", Name = "getCustomer")]  
public IActionResult GetCustomerById([FromRoute] int Id)  
{  
        return LocalRedirectPermanent("~/api/customers");  
}

What is the 400 HTTP Status Code?

This generic code of 4xx series indicates the request received from the client is a bad one. It may be due to a parameter mismatch, invalid data type, or other violations of the business rule.

ASP.NET returns 400 using the BadRequest() method:

[HttpPost("")]  
public IActionResult AddItem([FromBody] Item model)  
{  
    Var obj = db.CreateItem(model)
    If(obj.NotFound())  
    return BadRequest();  // returns 400 status code  
}

What is the 404 HTTP Status Code?

The 404 HTTP status code is used to indicate that the resource the client is looking for is not found or is not available. The server may choose a 410 status code instead of 404 if the resource was available on the requested location (URI) before the request was made.

ASP.NET has a NotFound() method that is used to return a 404 status code:

[HttpGet]  
[Route("{id}", Name = "getCustomerRoute")]  
public IActionResult GetCustomerById([FromRoute] int Id)  
{  
    var customer = CustomerData().Where(x => x.Id == Id).FirstOrDefault();  
    if (customer == null)  
    {  
        return NotFound();  
    }  
    return Ok(customer);  
}  

Read: Project Management Software for .NET Developers

What is the 500 HTTP Status Code?

This error indicates that the server has run into a problem that prevented it from completing the client’s request. 5xx series status codes include the following status codes:

  • 500 Status Code: Internal Server Error
  • 501 Status Code: Not Implemented
  • 502 Status Code: Bad Gateway
  • 503 Status Code: Service Not Available
  • 504 Status Code: Gateway Timeout
  • 507 Status Code: Insufficient Storage

The following ASP.NET code depicts how developers can return a 500 status code in scenarios where the server is not able to process the client’s request and put some additional information regarding the error in the response body:

public ActionResult GetCustomerOrder(string input)
{
    var request = new EntityRequestDto
    {
        Id = input
    };

    var response = GetCustomerOderDetail(request);

    if (response.IsSuccess)
    {
        return Ok(response.Value);
    }
    else{
    return StatusCode(StatusCodes.Status500InternalServerError, response.Error);
     }
}

Read more ASP.NET programming tutorials and software development guides.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Must Read