الانتقال إلى المحتوى
.NETASP.NET Core· 7 دقائق للقراءة

Why Middleware Order Matters: How the ASP.NET Core Pipeline Really Runs

Each app.Use call wraps everything registered after it. What a middleware can see, what it protects, and where your own middleware belongs.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

An API adds a small middleware that records who called which endpoint, for a compliance report. In production, every row says "anonymous", including calls made with valid tokens that the API accepted and answered. The middleware's code is fine. It's registered one line above app.UseAuthentication(), so when it runs, nobody has read the token yet.

The common misconception

The belief: 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.

Several things make that feel true. The order of 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.

But the 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

Each receives the request's 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:

C# Program.cs
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();

A request to / 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

Middleware hands information down the chain through the 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

The exception handler catches exceptions thrown by middleware registered after it, which is why the docs put it first. Register it below a middleware that throws, and the exception never reaches it: in production, the server answers with a bare 500 and no body instead of your error response. Authorization can stop a request before it reaches the endpoint, but any middleware registered before authorization has already run for that request. Place a check too late, and the work it was meant to prevent has already happened.

Some middleware ends the request early

A middleware that answers without calling 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

Both versions register the same services and the same audit code. Only its position changes:

C# Program.cs
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();

Call /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

MiddlewarePositionWhy
UseExceptionHandlerFirstIt only catches exceptions thrown after it
UseStaticFilesEarly, before routingIt answers file requests and ends them
UseRoutingBefore CORS, authentication and authorizationThey need the selected endpoint
UseCorsAfter routing, before authenticationRequired order from the docs
UseAuthenticationBefore anything that reads context.UserIt's what sets the user
UseAuthorizationAfter authentication, before the endpointsIt rejects requests the endpoint must not see

The table follows the order in Microsoft's docs. When in doubt, copy that order and move a middleware only when you can say what it needs to see and what it must protect.

How to apply it in your project

  1. Start from the documented orderLay out Program.cs as the docs do: exception handling, HSTS, HTTPS redirection, static files, routing, CORS, authentication, authorization, your own middleware, then the endpoints.
  2. Place custom middleware by what it needsIf it reads context.User, put it after UseAuthentication. If it reads the endpoint, put it after routing. If it must wrap everything, like timing or error logging, put it near the top.
  3. Test the pipeline, not only the endpointWrite 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.cs fails a test.
  4. Move growing middleware into a classTurn inline middleware into a class with an InvokeAsync method once it grows. It's created once at startup, so take scoped services as InvokeAsync parameters, 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 UseRouting or UseAuthentication calls replace the automatic ones at the position you choose.

📚 المصادر

  1. ASP.NET Core middleware: Middleware order — Microsoft Learn
  2. Routing in ASP.NET Core — Microsoft Learn
  3. Write custom ASP.NET Core middleware — Microsoft Learn

التعليقات (0)