When an HTTP request reaches your ASP.NET Core application, it doesn’t go straight to the controller, nor does it magically jump to your Minimal API endpoint.
First, it has to traverse something almost all of us use daily, but many people don’t fully understand: the middleware pipeline.
Each piece of middleware in that chain has the opportunity to:
- inspect the request
- modify the
HttpContext - short-circuit the flow right then and there
- or simply let the request continue its way to the next component
Thoroughly understanding how this pipeline works will save you from plenty of headaches. It is key to:
- implementing authentication and authorization properly
- logging useful info (without weird duplicates)
- catching and handling errors globally
- measuring real performance
- keeping your code clean and predictable
Let’s see step-by-step how it actually works.
What Is (and What Does It Look Like) the HTTP Pipeline?
In ASP.NET Core, the pipeline is simply a chain of middleware components through which the request passes.
Each middleware receives two important things:
- The
HttpContext(containing all request and response information) - A reference to the next middleware (usually called
next)
The flow looks roughly like this:
Request
↓
Middleware 1
↓
Middleware 2
↓
Middleware 3
↓
Endpoint (Controller / Minimal API)
↑
Middleware 3
↑
Middleware 2
↑
Middleware 1
↑
Response
Notice something crucial: the response travels back in the opposite direction.
This means a middleware can execute code before calling the next one… and also after all subsequent components have finished.
This two-phase execution (before + after) is what makes the middleware system so powerful.
A Simple Middleware to Get Started
Take a look at this classic logging example:
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation(
"Iniciando request {Method} {Path}",
context.Request.Method,
context.Request.Path);
await _next(context);
_logger.LogInformation(
"Finalizando request {Method} {Path} → {StatusCode}",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode);
}
}
What happens here?
- It receives the request -> logs “entering”
- It calls
await _next(context)-> hands control to the next component - Once everything else finishes (including the endpoint), it logs “exiting”
This before -> next -> after pattern is literally the foundation of almost everything you see in the pipeline.
How (and Where) Middlewares Are Registered
Everything is configured in Program.cs (or in the legacy Startup.cs if you are on older versions).
The direct approach:
app.UseMiddleware<RequestLoggingMiddleware>();
However, the common practice is to use the extension methods provided by the framework:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles(); // si sirve archivos estáticos
app.MapControllers(); // o MapRazorPages, MapMinimalApis, etc.
The order in which you define them is critical.
Pipeline Order: Where Most People Go Wrong
Underestimating pipeline order is a very common mistake.
A classic example of an incorrect configuration:
app.UseAuthorization(); // ¡mal!
app.UseAuthentication();
Why is this wrong? Because UseAuthorization needs to know who the user is (meaning it must have already gone through authentication).
The most common correct order would look something like this:
app.UseExceptionHandler("/error"); // lo más temprano posible (captura excepciones abajo)
app.UseHsts(); // seguridad
app.UseHttpsRedirection(); // redirección https
app.UseStaticFiles(); // archivos estáticos primero (rápido y barato)
app.UseRouting();
app.UseCors(); // si usas CORS
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers(); // o MapRazorPages, endpoints de Minimal API, etc.
If you put UseAuthentication after UseAuthorization, you will likely encounter ghost 401/403 errors that take hours to debug.
The Three Main Ways to Add Middleware
1. Use -> the most common: Allows executing code before and after.
app.Use(async (context, next) =>
{
// código antes
await next();
// código después
});
2. Run -> terminates the pipeline
It does not call anything else. It is used for terminal responses (for example, a custom 404 or a test “Hello World”).
app.Run(async context =>
{
await context.Response.WriteAsync("¡Hola desde el final del pipeline!");
});
3. Map (and MapWhen) -> conditional sub-pipelines
Useful for applying middleware only to specific routes.
app.Map("/api", api =>
{
api.UseMiddleware<ApiSpecificLoggingMiddleware>();
api.UseMiddleware<RateLimitingMiddleware>();
});
Dependency Injection Inside Middlewares
One of the best features of ASP.NET Core is that you can inject services directly into the middleware constructor:
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
private readonly ICurrentUserService _userService;
public RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger,
ICurrentUserService userService)
{
_next = next;
_logger = logger;
_userService = userService;
}
// ...
}
The DI container resolves everything automatically. This lets you plug in logging, metrics, business services, etc., without jumping through hoops.
Common Mistakes I See Time and Time Again
- Forgetting to call
await next()-> the request hangs indefinitely - Running heavy queries or reading large files inside a middleware -> it executes on every single request
- Resolving services manually with
context.RequestServices.GetService<...>()-> constructor injection is always preferred - Messing up the order (especially with routing, authentication, and authorization)
When Is It Worth Creating Custom Middleware?
Not everything needs to be middleware, but they shine when solving cross-cutting concerns that affect many (or all) requests:
- Structured request/response logging
- Global exception handling
- Metrics and Prometheus/OpenTelemetry integration
- Auditing sensitive operations
- Rate limiting / throttling
- Adding security headers (CSP, Permissions-Policy, etc.)
- Correlation IDs for distributed tracing
If the logic must run “always” or “almost always,” it is a prime candidate for middleware.
Wrapping Up: Why Should You Care About the Pipeline?
The middleware pipeline is the core mechanism ASP.NET Core uses to process HTTP requests.
When you understand it well:
- You avoid weird behaviors that cost days of debugging
- You write cleaner, more predictable code
- You make the most of dependency injection and framework extensibility
- You can build reusable components that carry over into multiple projects
Take some time to review the middleware order in your current Program.cs. Often, simply reordering 3–4 lines fixes a problem that seemed impossible to crack.
And if anyone ever asks you, “Why isn’t my authentication working?” or “Where on earth is this request hanging?”, you already know where to start looking: the pipeline.
Keep on coding.