Status Code Results in Asp.net Core

Status Code Results in Asp.net Core
ASP.NET Core MVC offers a range of action results designed specifically to return these status codes along with optional messages.
Common Status Code Results
OkResult: Indicates a successful request (HTTP 200).
BadRequestResult: Indicates a client error (HTTP 400). Often used for invalid input.
NotFoundResult: Indicates that the requested resource was not found (HTTP 404).
UnauthorizedResult: Indicates that the request requires authentication (HTTP 401).
ForbiddenResult: Indicates that the user is not authorized to access the resource (HTTP 403).
StatusCodeResult: Allows you to return any arbitrary HTTP status code.
 
 
Using Status Code Results
Direct Instantiation:
return new BadRequestResult(); // Returns HTTP 400
return new NotFoundResult();   // Returns HTTP 404
 
 
Helper Methods:
return BadRequest();     // Returns HTTP 400
return NotFound();       // Returns HTTP 404
return Unauthorized();  // Returns HTTP 401
return StatusCode(403); // Returns HTTP 403
 
With Messages:
return BadRequest(“Invalid input data”);
return NotFound(“Resource not found”);
These helper methods are more concise and expressive than directly instantiating the result objects.
 
 
Code
// HomeController.cs
[Route(“book”)]
public IActionResult Index()
{
    // … (validation checks similar to the previous example) …
 
    if (bookId <= 0)
    {
        return BadRequest(“Book id can’t be less than or equal to zero”);
    }
 
    // Note the use of NotFound here
    if (bookId > 1000)
    {
        return NotFound(“Book id can’t be greater than 1000”);
    }
 
    if (Convert.ToBoolean(Request.Query[“isloggedin”]) == false)
    {
        return StatusCode(401); // Customizable status code
    }
 
    return File(“/sample.pdf”, “application/json”);
}
 
In this refined example, the validation logic remains the same. However, we’ve made the following changes:
Specific Status Codes:
We use BadRequest() for invalid input (e.g., bookId less than or equal to zero).
We use NotFound() when the bookId is out of the valid range (greater than 1000), as it could imply the requested book doesn’t exist.
 
Customizable Status Code:
For the authentication failure case (isloggedin is false), we use StatusCode(401) to return the standard 401 Unauthorized status code. You could also use return Unauthorized(); as a shortcut.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply