Explanation of HTTP Status Codes in C#
Explanation of HTTP Status Codes in C#
HTTP status codes are standard responses issued by servers to indicate the status of a client’s request. Here’s an explanation of the status codes from the image with examples in C#:
200 OK
Description: The request has succeeded.
public IActionResult Get()
{
return Ok(new { message = "Success" });
}
201 Created
Description: The request has been fulfilled and resulted in a new resource being created.
public IActionResult Post()
{
return Created("/api/resource/1", new { id = 1, name = "Resource" });
}
400 Bad Request
Description: The server could not understand the request due to invalid syntax.
public IActionResult Post([FromBody] Model model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Proceed with valid request
}
401 Unauthorized
Description: The client must authenticate itself to get the requested response.
public IActionResult Get()
{
if (!User.Identity.IsAuthenticated)
{
return Unauthorized();
}
// Proceed with authenticated request
}
403 Forbidden
Description: The client does not have access rights to the content.
public IActionResult Get()
{
if (!User.IsInRole("Admin"))
{
return Forbid();
}
// Proceed with authorized request
}
404 Not Found
Description: The server can not find the requested resource.
public IActionResult Get(int id)
{
var resource = _service.GetResource(id);
if (resource == null)
{
return NotFound();
}
return Ok(resource);
}
429 Too Many Requests
Description: The user has sent too many requests in a given amount of time (“rate limiting”).
public IActionResult Get()
{
// Assuming some rate limiting logic here
bool isRateLimited = _rateLimiter.IsRateLimited(User.Identity.Name);
if (isRateLimited)
{
return StatusCode(429, "Too Many Requests");
}
// Proceed with the request
}
500 Internal Server Error
Description: The server has encountered a situation it doesn’t know how to handle.
public IActionResult Get()
{
try
{
// Some logic here
}
catch (Exception ex)
{
return StatusCode(500, "Internal Server Error");
}
}