An HTTP request in ASP.NET Core does not go directly to a controller or endpoint. It travels through a sequence of middleware components known as the request pipeline. Each component can inspect the request, modify the response, invoke the next component, or terminate processing completely.
This model is powerful, but ordering mistakes can create subtle security and behavior problems. If authentication runs before the request has been routed, endpoint metadata may not be available. If CORS is placed incorrectly, browsers may not receive the expected headers. If exception handling is registered too late, exceptions from earlier components may escape centralized handling. In ASP.NET Core, where middleware is registered is as important as what it does.
How the middleware chain works
The pipeline is built from request delegates. A middleware commonly has two phases: it performs work before calling the next delegate, then performs response processing after that delegate completes. Requests move forward in registration order; responses return in reverse order.
app.Use(async (context, next) =>
{
// Request phase
await next();
// Response phase
});If next is not called, the pipeline stops at that point. This short-circuit behavior is useful for serving static files, returning authentication failures, enabling maintenance mode, or producing a custom response. It can also make every endpoint unreachable if the omission is accidental.
A practical default order
Every application has different requirements, but the following arrangement is a useful starting point for many production services:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRouting();
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();This is not a universal template. Minimal APIs, Razor Pages, Blazor applications, and static-file-only hosts may use different components. The key rule is that a middleware must be placed after the information it depends on has been created and before components that need its output.
Why exception handling belongs near the beginning
In production, UseExceptionHandler can handle exceptions thrown by later middleware and endpoints. For that reason, it is normally registered near the beginning of the pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error");
}Placing exception handling at the end may leave earlier components outside its scope. Development environments can use detailed exception pages, but stack traces and internal application details should not be exposed to external clients in production.
The relationship between routing, authentication, and authorization
UseRouting selects an endpoint for the incoming request. Endpoint metadata can then be used by authorization policies, rate-limiting rules, and other endpoint-aware features.
A common security sequence is:
UseRoutingselects the endpoint.UseAuthenticationestablishes the user identity.UseAuthorizationevaluates access policies.- Endpoint mappings such as
MapControllersorMapGetexecute the selected handler.
Authentication and authorization are different responsibilities. Authentication determines who the caller is. Authorization decides whether that identity is allowed to access the selected resource. Reversing these components can prevent endpoint policies from being evaluated correctly or leave handlers without the expected user context.
Positioning CORS correctly
CORS controls which browser origins may make cross-origin requests and which headers or methods are permitted. In many endpoint-based applications, the CORS middleware is placed after routing and before authentication and authorization.
builder.Services.AddCors(options =>
{
options.AddPolicy("Frontend", policy =>
{
policy.WithOrigins("https://frontend.example")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();Prefer explicit production origins instead of broad rules such as AllowAnyOrigin unless the application genuinely requires them. CORS is a browser access-control mechanism, not an authentication system and not a replacement for server-side authorization.
Static files and short-circuiting
UseStaticFiles can serve a matching file without invoking the rest of the pipeline. Registering it early can prevent dynamic middleware from doing unnecessary work for static resources.
However, ordering matters if static-file responses must receive compression or custom headers. A middleware registered before static files may observe or modify those requests; one registered after static files may never see responses that have already been short-circuited.
Writing custom middleware safely
Middleware instances are commonly reused for the lifetime of the application. Mutable state stored in instance fields can therefore be shared by concurrent requests and cause races or data leakage. Keep request-specific values in local variables, HttpContext.Items, or another request-scoped mechanism.
public sealed class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var started = Stopwatch.GetTimestamp();
await _next(context);
var elapsed = Stopwatch.GetElapsedTime(started);
_logger.LogInformation(
"HTTP {Method} {Path} completed with {StatusCode} in {ElapsedMs} ms",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
elapsed.TotalMilliseconds);
}
}If a middleware needs a scoped service, avoid accidentally capturing a scoped dependency in a long-lived constructor. Resolve request-scoped dependencies through the invocation method or another lifetime-appropriate design.
Testing pipeline behavior
Ordering problems are often difficult to detect with isolated unit tests. Add integration tests for at least these cases:
- An anonymous caller receives the expected response from a protected endpoint.
- An authenticated caller can pass the configured authorization policy.
- An unexpected exception becomes the application’s standard error response.
- A CORS request includes the expected response headers.
- A static-file request does not trigger unnecessary dynamic work.
Check more than status codes. Verify response headers, error bodies, authentication claims, and relevant logs. Also test both branches of custom middleware: the path that invokes next and the path that intentionally terminates processing.
Common mistakes
- Registering everything globally: Behavior needed by only a few endpoints may be better expressed with endpoint metadata, authorization policies, route groups, or filters.
- Confusing authentication with authorization: Authentication identifies the caller; authorization makes the access decision.
- Catching exceptions only inside controllers: Middleware can fail before an endpoint is selected or after it returns.
- Changing headers after the response has started: Some headers can no longer be modified once body transmission begins.
- Keeping mutable shared state: Concurrent requests can observe one another’s data or create race conditions.
Conclusion
The ASP.NET Core middleware pipeline is the behavioral and security backbone of the application. Build it deliberately: establish error handling early, then place HTTPS, static-file, routing, CORS, authentication, and authorization components according to the information each one requires.
For every middleware, ask three questions: What context does it need? Can it short-circuit the request? Does it need to modify the response after the next component finishes? A pipeline that is explicit, testable, and easy to reason about is more valuable than one that merely works in a happy-path demo.
0 Comments