ASP.NET Core Request Life Cycle




The request life cycle in ASP.NET Core defines the journey of an HTTP request from the moment it enters the server (Kestrel or IIS) until a response is sent back to the client. Mastering this flow helps developers build scalable, modular, and efficient applications.

1️⃣ Request Received by the Web Server

  • The client (browser, app, etc.) sends an HTTP request.
  • It reaches the web server — typically Kestrel.
  • If using IIS, it acts as a reverse proxy and forwards the request to Kestrel.

2️⃣ Middleware Pipeline Begins Execution

ASP.NET Core uses a middleware pipeline to process requests. Each middleware component can:

  • Inspect or modify the request
  • Execute logic (logging, authentication, authorization, etc.)
  • Short-circuit the pipeline or pass the request forward

Example Middleware Pipeline:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

Explanation:

  • UseRouting() matches the request URL to route definitions.
  • UseAuthentication() authenticates the user.
  • UseAuthorization() checks if the authenticated user has access rights.
  • UseEndpoints() executes the matched endpoint, typically a controller action.
💡 Pro Tip: The order of middleware is critical! For example, UseAuthentication() must come before UseAuthorization(), and both should be placed between UseRouting() and UseEndpoints().

3️⃣ Routing Middleware Selects the Endpoint

The UseRouting() middleware matches the URL to a defined route using:

  • Attribute routing
  • Conventional routing
GET /api/products/5 → ProductsController.Get(int id)

4️⃣ Dependency Injection Resolves Controller

Controllers are instantiated using constructor injection:

public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
}

5️⃣ Model Binding and Validation

ASP.NET Core binds route, query, or body data to method parameters or model classes and validates inputs using data annotations. If any validation fails, it automatically generates validation errors for the client.

public IActionResult AddProduct([FromBody] ProductDto product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    // Business logic here
}

Explanation: The framework automatically attempts to map incoming data to ProductDto. If validation fails (e.g., required fields missing), ModelState.IsValid will be false, and you can return an appropriate error response. This ensures valid input before processing it in the action method.

6️⃣ Action Method Executes

The resolved controller executes the action method containing the business logic (e.g., database operations, API calls).

7️⃣ Action Result is Returned

Returns can be:

  • Ok(), BadRequest(), NotFound(), CreatedAtAction(), Redirect(), etc.
  • ASP.NET Core serializes the response (e.g., to JSON)
return Ok(new { id = 1, name = "Laptop" });

8️⃣ Response Sent to Client

  • The response flows back through the middleware pipeline.
  • Response middleware (e.g., logging, compression) can modify it.
  • Response is sent back to the client.

📌 Summary of Request Life Cycle

  1. Request received by Kestrel/IIS
  2. Middleware pipeline begins
  3. Routing selects endpoint
  4. Controller created via DI
  5. Model binding & validation
  6. Action method runs
  7. Action result returned
  8. Response sent to client

💡 Why This Matters

  • Helps in debugging performance or routing issues
  • Ensures middleware is placed in the correct order
  • Clarifies how DI, routing, and controllers interact

📚 Further Reading

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features