Computer Science

HttpStatusCode netcore


• 200 OK()
• The request was successful, data is being returned.

                        // 200 OK
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
   var product = new { Id = id, Name = "Telefon" };

   if (id <= 0)
       return BadRequest("Invalid product id"); // 400

   return Ok(product); // 200
}
                    

201 Created()

New resource created successfully.

                         // 201 Created
[HttpPost]
public IActionResult CreateProduct([FromBody] string name)
{
   if (string.IsNullOrWhiteSpace(name))
       return BadRequest("Product name cannot be empty"); // 400

   var createdProduct = new { Id = 1, Name = name };

   return Created($"/api/products/{createdProduct.Id}", createdProduct); // 201
}
                    

204 NoContent()

The request was successful but there was no data returned.

                        // 204 NoContent
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
   if (id <= 0)
      return BadRequest("Invalid id"); // 400

   //delete product
   return NoContent(); // 204
}
                    

403 Forbidden()

No authorization, access prohibited.

                        // 403 Forbidden
[HttpGet("admin")]
public IActionResult GetAdminData()
{
   if (!User.IsInRole("Admin"))
      return Forbid(); // 403

   return Ok("Admin data");
}
                    

404 NotFound()

The requested resource was not found.

                        // 404 NotFound
[HttpGet("search/{id}")]
public IActionResult SearchProduct(int id)
{
   if (id == 99) // no product
      return NotFound("No product"); // 404

   return Ok(new { Id = id, Name = "Laptop" });
}