A key idea in ASP.NET Core, middleware specifies how the application pipeline handles HTTP requests and responses. Before reaching the final endpoint, each request travels through a series of middleware components, each of which has the ability to examine, alter, or short-circuit the request. Building scalable, secure, and stable online applications requires an understanding of middleware.

 

How Middleware Works?
ASP.NET Core uses a request pipeline where each middleware component:

  • Receives an HTTP request
  • Performs some logic
  • Calls the next middleware in the pipeline
  • Optionally modifies the response

This pipeline is configured in Program.cs.

Middleware Pipeline Flow

Request → Middleware 1 → Middleware 2 → Middleware 3 → Endpoint
Response ← Middleware 1 ← Middleware 2 ← Middleware 3 ← Endpoint

Each middleware has control before and after the next middleware executes.

Basic Middleware Example

app.Use(async (context, next) =>
{
    Console.WriteLine("Request Incoming");

    await next();

    Console.WriteLine("Response Outgoing");
});


Explanation:

  • Code before next() runs during request processing
  • Code after next() runs during response processing

Types of Middleware

1. Built-in Middleware

ASP.NET Core provides several built-in middleware components:

  • Authentication Middleware
  • Authorization Middleware
  • Static Files Middleware
  • Routing Middleware
  • Exception Handling Middleware

Example:
app.UseAuthentication();
app.UseAuthorization();


2. Custom Middleware
You can create your own middleware to handle specific requirements.

Example: Custom Logging Middleware
public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");

        await _next(context);

        Console.WriteLine($"Response Status: {context.Response.StatusCode}");
    }
}


Register Custom Middleware
app.UseMiddleware<LoggingMiddleware>();

Middleware Execution Order
Order matters in middleware configuration.

Example:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();


Incorrect ordering can lead to issues such as:

  • Authentication not working
  • Endpoints not being reached
  • Middleware being skipped

Short-Circuiting Middleware
Middleware can stop further processing by not calling next().
app.Use(async (context, next) =>
{
    if (!context.Request.Headers.ContainsKey("Auth"))
    {
        context.Response.StatusCode = 401;
        await context.Response.WriteAsync("Unauthorized");
        return;
    }

    await next();
});

Real-World Use Cases
Middleware is commonly used for:

  • Logging requests and responses
  • Authentication and authorization
  • Exception handling
  • Request validation
  • Performance monitoring

Best Practices

  • Keep middleware lightweight and focused
  • Maintain correct order in pipeline
  • Avoid heavy processing inside middleware
  • Use built-in middleware when possible

Common Mistakes to Avoid

  • Incorrect middleware ordering
  • Forgetting to call next()
  • Adding unnecessary middleware
  • Handling business logic inside middleware

Conclusion
Middleware is the backbone of the ASP.NET Core request pipeline. It provides a powerful way to intercept, process, and manage HTTP requests and responses. By understanding middleware, developers can build flexible and efficient applications with better control over request processing.