ASP.NET  

How to Return Different HTTP Status Codes From ASP.NET Core Web API?

Introduction

When building real-world applications using ASP.NET Core Web API, returning correct HTTP status codes is not just a technical detail—it is a critical part of API design. HTTP status codes act as a communication contract between your backend (API) and frontend (UI, mobile app, or external systems).

In real production systems like e-commerce apps, banking systems, or booking platforms, improper status codes can lead to failed transactions, incorrect UI behavior, and poor debugging experiences.

In this detailed guide, we will deeply understand HTTP status codes in ASP.NET Core with:

  • Clear definitions

  • Real-world examples

  • Practical use cases

  • Advantages and disadvantages

  • Best practices used in industry

What Are HTTP Status Codes?

HTTP status codes are standardized response codes sent by the server to indicate the result of a client request.

Real-Life Analogy

Think of HTTP status codes like a delivery system:

  • 200 → Your package is delivered successfully

  • 404 → Address not found

  • 500 → Something broke in the delivery system

These codes help the client understand exactly what happened.

Categories of HTTP Status Codes

1xx – Informational

Used rarely in APIs. Indicates request is being processed.

2xx – Success

Indicates the request was successfully processed.

3xx – Redirection

Client needs to take additional action.

4xx – Client Errors

Client made a mistake (invalid input, unauthorized access).

5xx – Server Errors

Something went wrong on the server.

👉 In ASP.NET Core Web APIs, 2xx, 4xx, and 5xx are most commonly used.

Why HTTP Status Codes Matter in Real Projects

1. Better Frontend Integration

Frontend apps rely on status codes to decide UI behavior.

Example:

  • 200 → Show data

  • 404 → Show “Not Found” page

  • 500 → Show error message

2. Easier Debugging

Developers can quickly identify where the issue occurred.

3. Standard API Design (RESTful APIs)

Using correct status codes makes your API professional and scalable.

4. SEO & System Reliability

Search engines and monitoring tools rely on correct status codes.

How ASP.NET Core Returns Status Codes

ASP.NET Core provides built-in helper methods inside ControllerBase.

These methods automatically set the correct HTTP status code and response format.

Detailed Explanation of Common HTTP Status Codes

200 OK

Definition

The request was successful, and the server returned the expected data.

Example

return Ok("Data fetched successfully");

Real-World Use Case

  • Fetching product list

  • Getting user profile

Advantages

  • Simple and clear success response

Disadvantages

  • Misuse: Some developers return 200 even when errors occur

201 Created

Definition

Used when a new resource is successfully created.

Example

return Created("/api/users/1", new { Id = 1, Name = "John" });

Real-World Use Case

  • User registration

  • Creating an order

Advantage

  • Clearly indicates resource creation

Disadvantage

  • Requires proper resource URL handling

204 No Content

Definition

Request succeeded but no data is returned.

Example

return NoContent();

Real-World Use Case

  • Deleting a record

  • Updating without returning data

Advantage

  • Reduces response payload size

Disadvantage

  • Cannot send confirmation data

400 Bad Request

Definition

Client sent invalid or incomplete data.

Example

if (string.IsNullOrEmpty(name))
    return BadRequest("Name is required");

Real-World Use Case

  • Form validation errors

  • Missing required fields

Advantage

  • Helps client fix request quickly

Disadvantage

  • Needs proper validation logic

401 Unauthorized

Definition

User is not authenticated.

Example

return Unauthorized();

Real-World Use Case

  • Missing or invalid token

Advantage

  • Enforces authentication

Disadvantage

  • Often confused with 403

403 Forbidden

Definition

User is authenticated but not allowed to access the resource.

Example

return Forbid();

Real-World Use Case

  • Normal user trying to access admin panel

404 Not Found

Definition

Requested resource does not exist.

Example

return NotFound("User not found");

Real-World Use Case

  • Product not available

  • Invalid ID

500 Internal Server Error

Definition

Unexpected server failure.

Example

return StatusCode(500, "Server error occurred");

Real-World Use Case

  • Database failure

  • Unhandled exceptions

Difference Between 400 vs 401 vs 403 vs 404

Status CodeMeaningWhen to UseExample
400Bad RequestInvalid inputMissing required field
401UnauthorizedNot logged inNo token provided
403ForbiddenNo permissionUser accessing admin API
404Not FoundResource missingProduct ID not found

Returning Custom Status Codes

You can use StatusCode() method for flexibility.

return StatusCode(503, "Service temporarily unavailable");

Real-World Use Case

  • External API failure

  • Maintenance mode

Using ActionResult (Best Practice)

Definition

Strongly typed responses improve readability and API documentation.

public ActionResult<string> Get()
{
    return Ok("Hello API");
}

Advantage

  • Better Swagger documentation

  • Clear return types

Real-World Scenario (Complete Example)

[HttpGet("order/{id}")]
public IActionResult GetOrder(int id)
{
    if (id <= 0)
        return BadRequest("Invalid order ID");

    if (id != 100)
        return NotFound("Order not found");

    return Ok(new { Id = 100, Item = "Laptop" });
}

Flow Explanation

  • Invalid input → 400

  • Not found → 404

  • Success → 200

Best Practices for HTTP Status Codes

  • Never return 200 for errors

  • Use proper status codes based on situation

  • Keep error messages clear

  • Use global exception handling

  • Follow REST standards strictly

Summary

Understanding and correctly using HTTP status codes in ASP.NET Core Web API is essential for building scalable, maintainable, and professional APIs. Proper status codes improve communication between systems, simplify debugging, and enhance user experience. By applying real-world practices and using built-in ASP.NET Core methods, you can create APIs that follow industry standards and perform reliably in production environments.