Volume 2 · Chapter 3 — ASP.NET Core Enterprise Development
Middleware Deep Dive
3.1 Introduction
Middleware is the heart of ASP.NET Core’s request processing. Every application is a pipeline of middleware components, each of which can inspect the request, do work, call the next component, act on the response, or short-circuit the pipeline entirely. Middleware is where cross-cutting concerns - logging, correlation IDs, exception handling, authentication, authorization, rate limiting - belong, so they are applied uniformly to every request instead of being duplicated across business code.
3.2 The Pipeline Is a Nesting of Delegates
The key mental model is that middleware wraps the next component: it runs codebeforecallingnext, then the rest of the pipeline runs, then it runs codeafter. So requests flow inward in registration order and responses flow back outward in reverse order - like a set of nested function calls.
sequenceDiagram autonumber participant C as Client participant A as Middleware A participant B as Middleware B participant EP as Endpoint C->>A: request A->>B: (pre-work) call next B->>EP: (pre-work) call next EP-->>B: result B-->>A: (post-work on response) A-->>C: (post-work on response) Note over A,EP: In on the way down, out in reverse on the way back
3.3 Custom Middleware
A middleware component takes the nextRequestDelegateand implements anInvoke(orInvokeAsync) method that receives theHttpContext. This is where you add cross-cutting behavior like correlation IDs or timing.
public sealed class CorrelationMiddleware
{
private readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var id = context.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? Guid.NewGuid().ToString();
context.Response.Headers["X-Correlation-Id"] = id;
using (context.RequestServices.GetRequiredService<ILogger<CorrelationMiddleware>>()
.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id }))
{
await _next(context); // everything downstream logs with this correlation id
}
}
}
3.4 Ordering Is Everything
Middleware runs in registration order, and order is critical because each component depends on the previous ones having run. The canonical example is that authentication must run before authorization, because authorization needs the user identity that authentication establishes. Getting the order wrong causes authentication failures, missing headers, or CORS problems.
app.UseExceptionHandler("/error"); // outermost - catches everything below
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication(); // must run before authorization
app.UseAuthorization();
app.MapControllers(); // endpoint execution
3.5 Short-Circuiting
A middleware short-circuits the pipeline bynotcallingnext- responding directly instead. This is how efficient rejection works: an auth failure, a rate-limit exceeded, an invalid request, or maintenance mode returns immediately without running the expensive downstream work.
public async Task InvokeAsync(HttpContext context)
{
if (!IsValid(context))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
return; // short-circuit: pipeline stops here
}
await _next(context);
}
3.6 Built-in Middleware and Cross-Cutting Concerns
| Middleware | Purpose |
|---|---|
| Exception handler | Centralized error handling and consistent error responses |
| Authentication | Establishes the user identity (claims principal) |
| Authorization | Enforces access rules using the identity |
| Routing | Matches requests to endpoints |
| CORS | Controls cross-origin access |
| Rate limiting | Protects against overload and abuse |
Why must authentication middleware run before authorization middleware?
Because authorization decisions require a known identity, and authentication is what establishes that identity. Authentication middleware inspects the request’s credentials - a JWT bearer token, a cookie, etc. - validates them, and, if valid, builds theClaimsPrincipal(the user with their claims) and attaches it toHttpContext.User. Authorization middleware then evaluates whether that user is allowed to access the endpoint, using their claims, roles, and any policies. If authorization ran first,HttpContext.Userwould not yet be populated (or would be anonymous), so authorization would have no identity to evaluate and would either wrongly deny everything or, worse, wrongly allow it. The pipeline orderUseAuthentication()thenUseAuthorization()ensures the identity exists before access rules are checked. This is the canonical illustration of why middleware ordering matters: each component depends on the previous ones having done their work, and getting this particular order wrong breaks security entirely - which is why it’s a common interview question and a common real bug.
How does middleware execute, and what does it mean to short-circuit the pipeline?
Middleware executes as a chain of nested delegates: each component runs some code, then callsnextto invoke the rest of the pipeline, then runs more code afternextreturns. So on the way “in,” components run in registration order down to the endpoint; on the way “back out,” they resume in reverse order to act on the response. This lets a single component do work both before (e.g. start a timer, add a correlation id) and after (e.g. log the status code, stop the timer) the downstream processing. Short-circuiting means a middleware choosesnotto callnext, ending the pipeline early and producing the response itself. This is how efficient rejection and early responses work: an authentication failure returns 401, a rate limiter returns 429, an invalid request returns 400, or a maintenance-mode middleware returns 503 - all without running the expensive downstream middleware and endpoint. Short-circuiting is valuable for performance and security because it stops unnecessary work as early as possible; you place such gating middleware early in the pipeline so rejected requests do minimal work. The two ideas together - ordered nested execution and optional short-circuiting - are what make the middleware pipeline both powerful and something you must reason about carefully when ordering components.
What is the difference between middleware and MVC filters, and when do you use each?
Both handle cross-cutting concerns, but at different levels of the request pipeline and with different scope. Middleware operates at the HTTP-pipeline level, running foreveryrequest that reaches that point in the pipeline, before and around routing and endpoint execution; it works with the rawHttpContextand knows nothing about MVC concepts like actions, model binding, or action results. Use middleware for truly global, framework-agnostic concerns: exception handling, HTTPS redirection, authentication, correlation ids, rate limiting, response compression - things that should apply to all requests regardless of how they’re handled. Filters are an MVC concept that run within the MVC action-invocation pipeline, so they have access to MVC context - the action being invoked, its arguments (after model binding), and the action result - and can be scoped to specific controllers or actions via attributes. Use filters for concerns tied to MVC actions: model-validation handling, action-specific authorization, result transformation, action-level caching, or logging that needs to know the action and its bound parameters. There are several filter types (authorization, resource, action, exception, result) that run at specific points around action execution. In short: middleware for global, HTTP-level, MVC-unaware concerns across all requests; filters for MVC-aware concerns scoped to controllers/ actions with access to action context. Many apps use both - middleware for the outer, global layer and filters for finer-grained, action-specific behavior.
Multiple teams have added inconsistent exception handling in their controllers, producing different error responses. How do you fix this systemically?
This is a cross-cutting concern that has been wrongly duplicated in business code, so the fix is to centralize it in the pipeline and remove the scattered handling. I’d introduce a single global exception- handling mechanism - exception-handling middleware (or the built-inUseExceptionHandler/IExceptionHandler, or a problem-details based handler) placed at the outer edge of the pipeline - that catches unhandled exceptions from anywhere downstream and produces one consistent error contract for the whole API. That contract would be standardized (ideally RFC 7807 problem-details), always including a stable error code, a safe human-readable message, and a correlation id, while never leaking internal details or stack traces to clients. The middleware also logs the failure with full context and the correlation id, so operations get consistent, searchable error telemetry. Domain-specific exceptions map to appropriate status codes centrally (e.g. a not-found exception → 404, a validation exception → 400). Then I’d remove the ad-hoc try/catch blocks from controllers so they no longer each invent their own error shape, letting exceptions bubble to the central handler - controllers stay thin and focused on the happy path. To make this stick across teams, I’d provide it as a shared library or template so every service inherits the same behavior by default, document the standard error contract, and add tests/linting to prevent regression. The principle is that error handling, like logging and security, is a cross-cutting concern that belongs in one place in the infrastructure, applied uniformly, rather than reimplemented inconsistently in every controller - which gives consumers a predictable error contract and gives operations consistent diagnostics.
3.7 Production Scenario
A banking API returns inconsistent error responses after multiple teams add their own try/catch handling in controllers - some return 500 with a stack trace, others a custom JSON shape. The team introduces centralized exception-handling middleware producing a consistent problem-details contract with an error code, safe message, and correlation id, logs every failure with context, and removes the ad-hoc handlers from controllers - giving consumers a predictable error contract and operations consistent telemetry.
Chapter Revision Notes
- The pipeline is nested delegates: in on registration order, out in reverse - act before and after next.
- Ordering is critical (e.g. authentication before authorization).
- Short-circuiting (not calling next) enables efficient early rejection.
- Cross-cutting concerns belong in middleware/filters, not duplicated in business code.
- Centralize exception handling for a consistent error contract.