
Why Middleware Order Matters: How the ASP.NET Core Pipeline Really Runs
- كاتب موثّق
- .NET 10
محتويات المقال
app.UseAuthentication(), so when it runs, nobody has read the token yet.
The common misconception
Program.cs is a list of features to switch on. As long as every middleware is registered, the order of the app.Use... calls doesn't matter; the framework works out when each one should run.
builder.Services.Add... registrations rarely matters. app.MapGet lines can go almost anywhere in the file and still work. If you don't call UseRouting, UseAuthentication or UseAuthorization yourself, WebApplication adds them for you in a sensible spot. And a wrong order almost never fails at startup: there's no exception, just behavior that's subtly off.
app.Use... calls aren't settings. Each one adds a step to a chain, and the chain runs in exactly the order you wrote.
What actually happens
The pipeline is a chain of nested calls
HttpContext and a next delegate that stands for everything registered after it. Code before await next(context) runs on the way in; code after it runs on the way out, once the rest of the pipeline has finished. So the first middleware you register sees the request first and the response last:
var app = WebApplication.CreateBuilder(args).Build();app.Use(async (context, next) =>{ Console.WriteLine("A: request in"); await next(context); Console.WriteLine("A: response out");});app.Use(async (context, next) =>{ Console.WriteLine("B: request in"); await next(context); Console.WriteLine("B: response out");});app.MapGet("/", () => "Hello"); // endpoints run at the end of the pipelineapp.Run();/ prints "A: request in", "B: request in", then "B: response out" and "A: response out". The endpoint runs in the middle, even though MapGet comes first in the file: endpoints added to WebApplication always execute at the end of the pipeline.
A middleware sees only what ran before it
HttpContext. Routing picks the endpoint, so the selected endpoint is always null before routing runs. Authentication reads the token or cookie and sets context.User, so anything that runs earlier sees an anonymous user. That's the audit bug: the middleware asked for the user before anyone had looked.
A middleware guards only what comes after it
Some middleware ends the request early
next is the pipeline: static files return a file, authorization returns a 401 or 403. Nothing registered after it runs for that request, while everything registered before it still runs its code after next. app.Run is the extreme case: its delegate is always terminal, so an app.Use written after it never runs at all.
The audit middleware, fixed
var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();var app = builder.Build();app.Use(async (context, next) =>{ // runs before authentication: no token has been read yet var user = context.User.Identity?.Name ?? "anonymous"; app.Logger.LogInformation("{User} -> {Path}", user, context.Request.Path); await next(context);});app.UseAuthentication();app.UseAuthorization();app.MapGet("/orders", () => "orders").RequireAuthorization();app.Run();var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();var app = builder.Build();app.UseAuthentication(); // reads the token and sets context.Userapp.Use(async (context, next) =>{ // before authorization, so rejected calls are logged too var user = context.User.Identity?.Name ?? "anonymous"; app.Logger.LogInformation("{User} -> {Path}", user, context.Request.Path); await next(context);});app.UseAuthorization();app.MapGet("/orders", () => "orders").RequireAuthorization();app.Run();/orders with a valid token for "alice". The first version answers 200 and logs "anonymous -> /orders". The second logs "alice -> /orders". A call without a token still gets a 401 in both, and the second version logs it too, because the audit runs before authorization rejects the request.
Where the common middleware goes
UseExceptionHandler | ||
UseStaticFiles | ||
UseRouting | ||
UseCors | ||
UseAuthentication | context.User | |
UseAuthorization |
How to apply it in your project
Start from the documented order Lay out Program.csas the docs do: exception handling, HSTS, HTTPS redirection, static files, routing, CORS, authentication, authorization, your own middleware, then the endpoints.Place custom middleware by what it needs If it reads context.User, put it afterUseAuthentication. If it reads the endpoint, put it after routing. If it must wrap everything, like timing or error logging, put it near the top.Test the pipeline, not only the endpoint Write an integration test that sends a real request through the app and checks the side effects, such as the audit entry or the 401, so a reordering in Program.csfails a test.Move growing middleware into a class Turn inline middleware into a class with an InvokeAsyncmethod once it grows. It's created once at startup, so take scoped services asInvokeAsyncparameters, not constructor parameters.
Key takeaways
Middleware runs in the order of the app.Use...calls for requests, and in reverse for responses.A middleware sees only what earlier middleware set, such as the user or the endpoint, and guards only what comes after it. Short-circuiting middleware ends the request; nothing registered after it runs. Endpoints always run at the end, and explicit UseRoutingorUseAuthenticationcalls replace the automatic ones at the position you choose.
التعليقات (0)