Explanation of HTTP Status Codes in C#

Ahmed Eprahim
2 min readJul 26, 2024

--

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");
}
}

--

--

Ahmed Eprahim

Hello, my name is 𝑨𝒉𝒎𝒆𝒅 𝑬𝒑𝒓𝒂𝒉𝒊𝒎. I'm a 𝑺𝒆𝒏𝒊𝒐𝒓 𝑺𝒐𝒇𝒕𝒘𝒂𝒓𝒆 𝑬𝒏𝒈𝒊𝒏𝒆𝒆𝒓, working in .𝐍𝐄𝐓 𝐓𝐞𝐜𝐡𝐧𝐨𝐥𝐨𝐠𝐢𝐞𝐬.