You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
aspnet-basics/3-http-responses-and-status...

2.0 KiB

HTTP Responses & Status Codes

Check http request format from frontend-basics

ASP.NET Status Codes

  • There are multiple possible status codes for each action
  • The ControllerBase which the controllers should inherit from includes result methods for creating ActionResult objects
    • All ActionResult objects implement IActionResult
    • Includes at least a status code, and can contain data such as view items or an error message
    • This result is processed into a response to then send to client

ASP.NET Result Methods

Status Code Result Method Use
200 - OK _Ok() GET, DELETE
201 - Created _Created() POST
204 - No content _NoContent() PUT, PATCH
400 - Bad request _BadRequest() POST, PUT, PATCH
404 - Not found _NotFound() All actions
Custom _StatusCode() All actions

ASP.NET Status Codes (continued)

[HttpGet("{id}")]

public IActionResult GetContactById(int id)

{

// Contacts = list of contact objects, fetched from some repository

var contact = Contacts.FirstOrDefault(c => c.Id == id);

if (contact == null)

{

return NotFound();

}

return Ok(contact);

}

The previous code first attempts to find a Contacts object using the ID provided in the URI parameter

If an item is not found, a 404 response is returned using NotFound()

Otherwise, the object is sent as a payload with a 200 OK code response using Ok(contact)

Exercise 1: Returning Status Codes

Without using parameter constraints, modify your number list method from Lecture 2, Exercise 2 to return a status code 400 (Bad Request) if k is smaller than one or larger than 100.

Add a helpful error message to the result for both cases. The message should be seen as a message body in the response.

Test with Swagger/Postman.