Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 52 ยท Middleware and the Request Pipeline

The Middleware Pipeline

Understand the ASP.NET Core request pipeline: Use, Run, Map and MapWhen, the next delegate, why order matters, short-circuiting and terminal middleware.

Every HTTP request that reaches an ASP.NET Core application passes through a pipeline: a chain of small components called middleware. One component logs the request, another handles exceptions, another serves static files, another checks who the user is, and one at the end runs your endpoint. Each can look at the request, decide whether to pass it on, and look at the response on its way back out. Almost every built-in feature of the framework (HTTPS redirection, CORS, authentication, routing, compression) is just middleware, so understanding the pipeline explains a great deal of ASP.NET Core.

In this lesson you will build pipelines with Use, Run, Map and MapWhen, learn what the next delegate really does, see why the order of registration is the most important rule, and meet short-circuiting and terminal middleware. The next lesson, Writing Custom Middleware, turns these ideas into reusable classes.

A pipeline is a chain of delegates

Technically, a middleware is a function that takes an HttpContext and a RequestDelegate called next (the rest of the pipeline) and returns a Task. The builder wires them together in the order you register them: the first one wraps the second, which wraps the third, and so on.

flowchart LR
    C["Client"] --> M1["Middleware 1"]
    M1 --> M2["Middleware 2"]
    M2 --> M3["Middleware 3"]
    M3 --> E["Endpoint"]
    E -.-> M3
    M3 -.-> M2
    M2 -.-> M1
    M1 -.-> C

Solid arrows: the request goes inward. Dotted arrows: the response comes back out in the opposite order.

Code before await next() runs on the way in. Code after it runs on the way out, when the inner components have already produced the response. That is the "onion" you saw in the first overview lesson.

Use, Run and the next delegate

There are three basic registration methods:

  • app.Use(async (context, next) => ...) adds a middleware that may call next to continue.
  • app.Run(async context => ...) adds a terminal middleware. It has no next, so nothing after it ever runs.
  • app.Map... (next section) creates a branch.

Endpoints you add with MapGet and similar are part of the pipeline too, through two middleware that WebApplication adds for you: routing at the very start (it matches the URL and selects an endpoint) and the endpoint middleware at the very end (it runs the selected handler). Everything you register with Use sits between the two, so your middleware can already ask which endpoint was chosen (context.GetEndpoint()) before it runs.

C# Use, Run and the order of a trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For /hello the trace goes 1 in > 2 in > endpoint /hello > 2 out > 1 out. The endpoint handled the request, so the terminal Run never ran. For /other no endpoint matched, so the request fell through to Run, which produced the 404. This is also why app.Run is placed last: it is the "nobody else wanted this request" handler.

The explicit UseRouting() and UseEndpoints() calls are only there to make this demonstration possible. In a normal Program.cs you just call app.MapGet(...) and the framework runs endpoints at the end of the pipeline, after every Use and Run you wrote. So an app.Run(...) in Program.cs swallows every request before any endpoint can run, and an endpoint registered with plain MapGet is never reached. Use app.Run only for deliberate catch-alls inside branches, and use app.MapFallback(...) for an app-wide "nothing matched" endpoint.

app.Use has two overloads for the next delegate: next() with no arguments (the same HttpContext is reused) and next(context). They behave the same. Prefer the parameterless one in new code; it is shorter and avoids accidentally passing a different context.

Short-circuiting

A middleware that does not call next ends the request right there; inner components never see it. This is called short-circuiting, and it is how many built-in features work: static files returns the file, CORS answers a preflight, authorization returns 401, and the exception handler returns an error page.

C# A middleware that short-circuits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only one request reached the endpoint. The gate answered the other itself and simply returned without calling next.

Order matters

Because each middleware wraps the ones after it, registration order is execution order, and the wrong order produces bugs that look like magic. The classic examples:

  • The exception-handling middleware must be registered first, so it can catch exceptions thrown by everything inside it.
  • Authentication must run before authorization, and both before the endpoint.
  • Static files are usually placed before routing so image requests do not pay for routing and authentication.
  • CORS must be before the middleware that would end the request.

Here is a small proof. The same two components are registered in different orders in two apps: a gate that rejects requests without a header, and a stamp that adds a header to every response it sees.

C# The same middleware in a different order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When the stamp is first, even the blocked response carries it, because the stamp sits outside the gate and its OnStarting callback is registered before the gate short-circuits. When the gate is first, blocked requests never reach the stamp. Neither order is "right": what matters is that you decide which components should see which requests.

(Use accepts a Func<RequestDelegate, RequestDelegate> too, which is the raw form every middleware is compiled to. The (context, next) lambdas you have been writing are shorthand for it.)

Branching: Map, MapWhen and UseWhen

Sometimes part of the app needs its own mini-pipeline. Three methods create branches:

Method Branch is chosen when Rejoins the main pipeline?
Map("/admin", branch => ...) the path starts with /admin No: the branch is terminal
MapWhen(predicate, branch => ...) the predicate on HttpContext is true No: the branch is terminal
UseWhen(predicate, branch => ...) the predicate is true Yes: after the branch, execution continues in the main pipeline

Map also moves part of the path: inside the branch, context.Request.Path has the matched prefix removed and PathBase holds it. That is what lets a branch be mounted anywhere.

flowchart TD
    R["Request"] --> M{"Map /admin ?"}
    M -- yes --> B1["Admin branch<br/>(its own middleware)"]
    M -- no --> W{"MapWhen: has ?debug ?"}
    W -- yes --> B2["Debug branch"]
    W -- no --> MAIN["Main pipeline<br/>and endpoints"]

Map and MapWhen send a request into a separate branch that does not come back. Requests that match neither continue down the main pipeline.

C# Map, MapWhen and UseWhen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

/admin/users/7 entered the admin branch, where the matched prefix moved into PathBase and the rest stayed in Path. /?debug=1 was caught by the MapWhen condition even though / would otherwise match an endpoint. And the UseWhen header appears only on the /api response, but the request still reached the normal endpoint because UseWhen rejoins.

In everyday apps you rarely need Map with Run branches. Endpoint routing with route groups handles URL-based structure. Reach for UseWhen when you want a middleware to apply only to some requests, and for Map/MapWhen to host a completely separate pipeline such as a health or diagnostics endpoint.

Terminal middleware and the response rules

A terminal middleware ends the pipeline: app.Run, a Map branch's Run, and every endpoint are terminal. Anything registered after a terminal component on the same branch is unreachable, which is a common silent mistake.

Two response rules matter in every middleware:

  1. Once the response has started (the first body bytes or headers were sent), you cannot change the status code or headers. Check context.Response.HasStarted, or use OnStarting to add headers at the last moment, as the stamp above did.
  2. Do not write to the body and then call next unless you know the inner components will not write: two writers produce a garbled response or an exception.

HttpContext, Request and Response covers these details further.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Middleware A is registered before middleware B with app.Use. Which sequence describes one request that reaches the endpoint?

    The first registered middleware is the outermost layer. The request travels inward A then B to the endpoint, and the response travels outward B then A.
  2. 2. What is the difference between app.Use and app.Run?

    app.Use gives you next so you can pass the request on. app.Run adds a terminal middleware: nothing after it executes.
  3. 3. How does app.UseWhen differ from app.MapWhen?

    With UseWhen the branch is a detour: when it calls next, the main pipeline continues. MapWhen creates a separate terminal branch.
  4. 4. Why should the exception-handling middleware be registered first?

    A middleware can only catch exceptions from the components inside it. Registering the exception handler first puts everything else inside its try block.
  5. 5. Inside an app.Map("/admin", ...) branch, a request for /admin/users/7 has which Path and PathBase?

    Map removes the matched prefix from Path and appends it to PathBase, so links and routing inside the branch work relative to the mount point.

Summary

  • The pipeline is a chain of middleware: each can act before next, call it, and act after it on the way out.
  • Use adds middleware that can continue, Run adds terminal middleware, and endpoints are terminal too.
  • A middleware that does not call next short-circuits the request.
  • Registration order is execution order; exception handling goes first, authentication before authorization.
  • Map and MapWhen create terminal branches; UseWhen creates a branch that rejoins the main pipeline; Map moves the matched prefix into PathBase.
  • After the response has started, status and headers can no longer change; use OnStarting to add headers late.

Next: Writing Custom Middleware