The middleware pipeline
Middleware are the steps a request passes through between reaching the server and the response being sent. Together they form the middleware pipeline, and its order decides what runs, what is skipped and what can short circuit the request.
41.1 Why is it used?
- Cross-cutting work (API key checks, timing, logging, correlation ids, error handling) is written once instead of in every endpoint.
- Every middleware sees both the request (on the way in) and the response (on the way out).
- A middleware can stop a bad request early (short circuit) so the endpoint never runs.
- ASP.NET Core features themselves (HTTPS redirection, static files, authentication, authorization, routing) are middleware.
41.2 The bug: the key check never ran
var app = WebApplication.Create(args); app.Run(context => context.Response.WriteAsync("3 orders")); app.Use(async (context, next) =>{ var headers = context.Request.Headers; if (headers["X-Api-Key"] == "secret-123") await next(context); else context.Response.StatusCode = 401;}); app.Run();$ curl -i localhost:5041/ordersHTTP/1.1 200 OKServer: KestrelTransfer-Encoding: chunked 3 orders- Middleware runs in exactly the order you register it.
- Run is terminal: it never gets a next step, so the request ends there and the response goes back.
- Any middleware written after Run never executes, so the security check was silently skipped (200 OK and 3 orders without a key).
- Step 1
1.Register order = run order
- Step 2
2.Run comes first and writes "3 orders"
- Step 3
3.Run is terminal: no next
- Step 4
4.Use (key check) after Run never runs
Middleware after Run is dead code
41.3 Fix: Use before Run
var app = WebApplication.Create(args); app.Use(async (context, next) =>{ var headers = context.Request.Headers; if (headers["X-Api-Key"] == "secret-123") await next(context); else context.Response.StatusCode = 401;}); app.Run(context => context.Response.WriteAsync("3 orders")); app.Run();$ curl -i localhost:5041/ordersHTTP/1.1 401 UnauthorizedContent-Length: 0Server: Kestrel $ curl -i localhost:5041/orders \ -H "X-Api-Key: secret-123"HTTP/1.1 200 OKServer: Kestrel 3 orders- Use gets two things: context (the current request) and next (the next step of the pipeline).
- Correct key: await next(context) passes the request on.
- Wrong or missing key: StatusCode = 401 and next is not called, so the request goes no further. This is a short circuit.
41.4 Use: code before and after next
var app = WebApplication.Create(args);var clock = TimeProvider.System; app.Use(async (context, next) =>{ var start = clock.GetTimestamp(); await next(context); var ms = clock.GetElapsedTime(start); Console.WriteLine($"{context.Request.Path} " + $"{context.Response.StatusCode} " + $"{ms.TotalMilliseconds:F1} ms");}); app.MapGet("/orders", () => "3 orders");app.Run();$ dotnet run --urls http://localhost:5041info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5041/orders 200 8.2 ms/orders 200 0.2 ms- Code before await next runs on the way in (start time).
- await next runs the rest of the pipeline and the endpoint.
- Code after it runs on the way back (elapsed time, path, status code).
- The first request is slower (8.2 ms vs 0.2 ms) because of warm up.
- Step 1
1.Request in: A -> B -> endpoint
- Step 2
2.Endpoint builds the response
- Step 3
3.Response out: B -> A (reverse order)
- Step 4
4.Any middleware that skips next = short circuit, stop here
Registration decides the order
41.5 Checkpoint: what gets printed?
app.Use(async (context, next) =>{ Console.WriteLine("A in"); await next(context); Console.WriteLine("A out");});app.Use(async (context, next) =>{ Console.WriteLine("B in"); await next(context); Console.WriteLine("B out");});app.Run(context => context.Response.WriteAsync("Done"));$ curl localhost:5041/Done# server consoleA inB inB outA out- On the way in A runs first, on the way back B finishes first: A in, B in, B out, A out.
41.6 Use, Run and Map
var app = WebApplication.Create(args);app.Map("/admin", admin =>{ admin.Use(async (context, next) => { Console.WriteLine("Admin branch"); await next(context); }); admin.Run(context => context.Response.WriteAsync( $"Admin: {context.Request.Path}"));}); app.MapGet("/orders", () => "3 orders");app.Run();$ curl localhost:5041/admin/usersAdmin: /users# server console: Admin branch $ curl localhost:5041/orders3 orders- Map("/admin", ...) sends every request starting with /admin into a separate mini pipeline with its own Use and Run.
- Inside the branch the matched prefix is removed from Request.Path, so /admin/users prints only /users.
- Other requests (/orders) stay in the main pipeline.
| Method | Calls next? | What it does |
|---|---|---|
| Use | Yes (optional) | Runs code before/after next; can short circuit by not calling next |
| Run | No (terminal) | Ends the pipeline and writes the response; anything after it never runs |
| Map | Branches | Creates a separate pipeline for a path prefix; prefix is stripped from Path |
| UseMiddleware<T> | Yes | Registers a middleware class with InvokeAsync |
41.7 Custom middleware class
public class CorrelationIdMiddleware( RequestDelegate next){ public async Task InvokeAsync( HttpContext context) { var id = Guid.NewGuid().ToString()[..8]; context.Items["CorrelationId"] = id; context.Response.Headers ["X-Correlation-Id"] = id; await next(context); }}- In real projects middleware goes in a class so it is reusable and testable.
- The constructor gets a RequestDelegate (the next step); InvokeAsync runs for every request.
- The id is stored in HttpContext.Items and also put in a response header, before next (headers must be set before the response starts).
41.8 HttpContext: Request, Items, User
var app = WebApplication.Create(args);app.UseMiddleware<CorrelationIdMiddleware>(); app.MapGet("/orders", (HttpContext context) =>{ var id = context.Items["CorrelationId"]; var city = context.Request.Query["city"]; var user = context.User.Identity?.Name ?? "guest"; return $"{id}: orders for {user} in {city}";}); app.Run();$ curl -i "localhost:5041/orders?city=Pune"HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8X-Correlation-Id: ca16be1e ca16be1e: orders for guest in Pune- UseMiddleware<CorrelationIdMiddleware>() registers the class; .NET fills constructor dependencies from DI.
- HttpContext holds everything about one request.
- Items is a dictionary that lives only for this one request, so the endpoint reads the same id the middleware stored.
- Request.Query["city"] reads the query string; User.Identity?.Name is the logged in user (guest here, no authentication yet).
41.9 Common mistakes
- Registering Use after Run: it never runs.
- Setting a header after await next: the response has already started, so the server throws InvalidOperationException (headers are read-only).
- Myth: a Use written after MapGet runs after the endpoint. WebApplication puts endpoints at the end of the pipeline, so the output is middleware in -> endpoint -> middleware out. Run's position, however, does matter.
- Injecting scoped services in a middleware class constructor: the class is created only once, so take scoped services as InvokeAsync parameters.
Wrong: header after next.
app.Use(async (context, next) =>{ var start = clock.GetTimestamp(); await next(context); var ms = clock.GetElapsedTime(start); context.Response.Headers["X-Response-Ms"] = ms.TotalMilliseconds.ToString("F1");});// InvalidOperationException: Headers are// read-only, response has already started.Right: OnStarting registers a callback that runs just before the headers are sent.
app.Use(async (context, next) =>{ var start = clock.GetTimestamp(); context.Response.OnStarting(() => { var ms = clock.GetElapsedTime(start); context.Response.Headers["X-Response-Ms"] = ms.TotalMilliseconds.ToString("F1"); return Task.CompletedTask; }); await next(context);});// X-Response-Ms: 7.441.10 Middleware rules
- Order: exception handling -> HTTPS -> static files -> authentication/authorization -> endpoints.
- Use Run only at the end of the pipeline.
- Set headers before next or inside OnStarting.
- Put reusable logic in a middleware class.
- Scoped services go in InvokeAsync parameters, not the constructor.
- Step 1
1.UseExceptionHandler (catches everything below)
- Step 2
2.UseHttpsRedirection
- Step 3
3.UseStaticFiles
- Step 4
4.UseAuthentication -> UseAuthorization
- Step 5
5.Endpoints (MapGet / controllers)
Errors at the top, endpoints at the end
41.11 Interview tips
- Middleware is a component that handles both the request and the response; together they form a pipeline that runs in registration order.
- Use passes the request on by calling next, Run is terminal, Map creates a branch by path.
- The response passes back through middleware in reverse order; not calling next is a short circuit.
- Reusable middleware is a class with InvokeAsync registered with UseMiddleware; set headers before the response starts (or in OnStarting).