The Analogy: The Corridor of Checkpoints
Imagine a corridor with several desks in a row. Every visitor walks past each desk on the way in, and past each desk again on the way out. The first desk stamps a time on the visit card. The second checks a pass and can send the visitor straight back out of the building. The third notes what the visitor came for. Only after all the desks have had their turn does the visitor reach the office that actually does the work.
The corridor is not a queue of independent inspectors — it is nested. Desk one calls desk two, which calls desk three, which calls the office; then control unwinds back through three, two and one. That is why the first desk can stamp a start time on the way in and an end time on the way out with nothing more than a local variable: its code surrounds everything that happens inside. Anything wrapped around the whole request belongs at a desk near the front of the corridor.
An ASP.NET Core middleware component is one desk. It receives the HttpContext and a delegate called next, does whatever it does, and either calls next to continue down the corridor or returns without calling it, which sends the visitor back out immediately. That single decision — call next or not — is the whole mechanism behind authentication, caching, rate limiting, redirects and compression.
Because the corridor is nested, order is behaviour. Put the pass check before the desk that logs what the visitor wanted, and rejected visitors never appear in the log. Put the error handler after the thing that fails, and the error escapes into the street. Almost every confusing bug in a web application's cross-cutting concerns is a component in the wrong position, and reading Program.cs from top to bottom is reading the corridor from the front door inwards.
Syntax or Core Structure
A component is registered with app.Use, and the pipeline ends either at an endpoint or at a terminal delegate registered with app.Run. This program builds a three-desk corridor, sends two requests through it, and prints what each desk saw:
using System.Diagnostics;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); // keep the console output to our own lines
WebApplication app = builder.Build();
app.Urls.Add("http://127.0.0.1:5211");
// Lines are collected instead of printed directly, because two requests would
// otherwise interleave in the console. See the note under the output.
List<string> log = new List<string>();
void Log(HttpContext ctx, string message)
{
string tag = ctx.Request.Headers["X-Case"].ToString();
lock (log) { log.Add(tag + " " + message); }
}
// Desk 1: wraps everything. Its "out" line runs after the endpoint has finished.
app.Use(async (HttpContext ctx, RequestDelegate next) =>
{
Log(ctx, "timing in");
await next(ctx);
Log(ctx, "timing out " + ctx.Response.StatusCode);
});
// Desk 2: can short-circuit. Returning without calling next ends the request.
app.Use(async (HttpContext ctx, RequestDelegate next) =>
{
if (!ctx.Request.Headers.ContainsKey("X-Api-Key"))
{
Log(ctx, "gate reject 401");
ctx.Response.StatusCode = 401;
await ctx.Response.WriteAsync("api key required");
return; // desk 3 and the endpoint never run
}
Log(ctx, "gate pass");
await next(ctx);
Log(ctx, "gate out");
});
app.MapGet("/orders", (HttpContext ctx) =>
{
Log(ctx, "endpoint handled");
return Results.Ok(new { count = 1 });
});
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5211") };
List<string> statuses = new List<string>();
await Send("1", withKey: false);
await Send("2", withKey: true);
await app.StopAsync(); // waits for the pipeline to unwind
// OrderBy is a stable sort, so lines stay in pipeline order within each case.
foreach (string line in log.OrderBy(l => l[0]))
{
Console.WriteLine(line);
}
Console.WriteLine();
foreach (string line in statuses)
{
Console.WriteLine(line);
}
async Task Send(string tag, bool withKey)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/orders");
request.Headers.Add("X-Case", tag);
if (withKey)
{
request.Headers.Add("X-Api-Key", "demo-value-not-a-real-key");
}
HttpResponseMessage response = await client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
statuses.Add(tag + " response " + (int)response.StatusCode + " " + body);
}
Output:
1 timing in
1 gate reject 401
1 timing out 401
2 timing in
2 gate pass
2 endpoint handled
2 gate out
2 timing out 200
1 response 401 api key required
2 response 200 {"count":1}
Read the output as an onion cut in half. Case 1 enters the timing desk, is rejected by the gate, and leaves through the timing desk again — the gate's own "out" line never appears because it returned instead of calling next. Case 2 goes all the way to the endpoint and unwinds in mirror order. The status code the timing desk prints on the way out is the final one, because by then everything inside has finished with the response.
The two requests are logged into a list rather than written straight to the console for a mundane reason: an HttpClient call can return before the server has finished unwinding its pipeline, so printing from both sides would produce an order that changes between runs. Collecting and sorting at the end removes the race without changing what the pipeline does.
Technical Depth: How the Pipeline Is Built
At startup, each Use call adds a function that takes the rest of the pipeline and returns a new RequestDelegate. When Build runs, ASP.NET Core folds that list from the back to the front, so the finished pipeline is one deeply nested delegate. await next(ctx) is a plain method call into the next layer; there is no queue, no dispatcher and no reflection at request time.
That explains the three registration verbs:
| Method | What it adds | Calls the rest of the pipeline? |
|---|---|---|
app.Use(...) | A component that receives next | Only if you call next(ctx) |
app.Run(...) | A terminal component | Never — it has no next |
app.Map("/path", branch) | A branch on a path prefix | Runs the branch instead, and strips the matched prefix from Request.Path |
app.UseWhen(pred, branch) | A conditional branch that rejoins | Runs the branch when the predicate is true, then continues down the main pipeline |
app.MapWhen(pred, branch) | A conditional branch that does not rejoin | Runs the branch and stops; the main pipeline below is skipped |
The canonical order
Most components only work if the ones they depend on have already run. This is the order the templates use, and the reasoning behind each position:
| Position | Component | Why here |
|---|---|---|
| 1 | UseExceptionHandler | Outermost, so it can catch failures from everything inside |
| 2 | UseHsts / UseHttpsRedirection | Move the client to HTTPS before any work is done |
| 3 | UseStaticFiles | Serve files without paying for routing, auth or sessions |
| 4 | UseRouting | Selects the endpoint; nothing downstream can read endpoint metadata before this |
| 5 | UseCors | Needs the endpoint's CORS policy metadata, so after routing |
| 6 | UseAuthentication | Turns credentials into a ClaimsPrincipal on ctx.User |
| 7 | UseAuthorization | Reads ctx.User and the endpoint's policies, so after both |
| 8 | UseResponseCaching / rate limiting | Needs the endpoint, and should sit inside auth |
| 9 | MapGet / MapControllers | The endpoint itself, innermost |
Middleware as a class
Inline lambdas are fine for two lines. Anything with dependencies, options or tests belongs in a class. The convention-based shape is not an interface — the framework finds it by name:
public sealed class ApiKeyMiddleware
{
private readonly RequestDelegate next;
private readonly string expectedKey;
// The constructor runs ONCE. Only singletons may be injected here.
public ApiKeyMiddleware(RequestDelegate next, IConfiguration config)
{
this.next = next;
this.expectedKey = config["Api:Key"] ?? string.Empty;
}
// Extra parameters here are resolved per request, so scoped services are safe.
public async Task InvokeAsync(HttpContext context, IAuditSink audit)
{
string supplied = context.Request.Headers["X-Api-Key"].ToString();
if (!string.Equals(supplied, expectedKey, StringComparison.Ordinal))
{
await audit.RecordAsync("rejected", context.Request.Path);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
await next(context);
}
}
// Registration:
app.UseMiddleware<ApiKeyMiddleware>();
The method must be called Invoke or InvokeAsync, must return Task, and must take HttpContext first. Everything after that is filled from the request's service scope.
| Concern | Convention-based class | IMiddleware implementation |
|---|---|---|
| Lifetime | Effectively a singleton, created once at startup | Resolved from DI on every request |
| Scoped dependencies | Inject into InvokeAsync, never the constructor | Constructor injection works normally |
| Registration | UseMiddleware<T>() only | Must also be registered in the container |
| Cost | No per-request allocation | One resolve per request |
The lifetime rule is the one that bites. Injecting a DbContext into a convention-based middleware's constructor compiles, then hands every request in the application's lifetime the same context instance — with its change tracker growing forever and no thread safety. The compiler cannot see the mistake; the runtime throws InvalidOperationException about a scoped service from the root provider only when scope validation is on, which is the default in Development and off in Production.
Once the response has started, it is too late
The first byte written to the body flushes the status line and headers. After that, ctx.Response.HasStarted is true and setting the status code or adding a header throws. Any component that wants the last word — an error handler, a header stamper — must either run before anything writes, or register a callback:
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Served-By"] = "orders-api";
return Task.CompletedTask;
});
Middleware or endpoint filter?
Middleware sees every request, including ones that match no route. An endpoint filter runs only for the endpoints it is attached to, after model binding, and can inspect and replace the bound arguments and the result. Use middleware for pipeline-wide concerns and filters for per-endpoint concerns.
| Need | Reach for |
|---|---|
| Correlation ids, timing, exception boundary, compression | Middleware |
| Validating one endpoint's arguments | Endpoint filter |
| Behaviour that must also apply to 404s and static files | Middleware |
| Behaviour that needs the bound parameters | Endpoint filter |
| Behaviour selected by endpoint metadata such as an attribute | Either, but the middleware must run after UseRouting |
Passing state along the corridor
ctx.Items is a per-request dictionary that lives and dies with the request. It is the normal way one component hands a value to another without a service. For anything richer — a resolved tenant, a parsed principal — prefer a scoped service that the middleware populates, so downstream code gets a typed dependency instead of a string key and a cast.
Real World Example: A Diagnostics Stack You Can Actually Debug
Every production service needs three things wrapped around it: a correlation id so one user's complaint can be traced through the logs, a boundary that turns unhandled exceptions into a clean JSON response, and an audit line recording the final status. Their order is not a matter of taste — get it wrong and the audit records 200 for requests that actually failed.
using System.Diagnostics;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddSingleton<RequestLog>();
WebApplication app = builder.Build();
app.Urls.Add("http://127.0.0.1:5212");
// Outermost, so it observes the status the error handler decides on.
app.UseMiddleware<AuditMiddleware>();
app.UseMiddleware<ProblemMiddleware>();
app.UseMiddleware<CorrelationIdMiddleware>();
app.MapGet("/ok", () => Results.Ok(new { ok = true }));
app.MapGet("/boom", IResult () => throw new InvalidOperationException("inventory feed offline"));
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5212") };
List<string> statuses = new List<string>();
await Send("1", "/ok", "trace-42");
await Send("2", "/ok", null); // no id supplied: one is generated
await Send("3", "/boom", "trace-77");
await app.StopAsync();
RequestLog requestLog = app.Services.GetRequiredService<RequestLog>();
foreach (string line in requestLog.Ordered())
{
Console.WriteLine(line);
}
Console.WriteLine();
foreach (string line in statuses)
{
Console.WriteLine(line);
}
async Task Send(string tag, string path, string? correlationId)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.Add("X-Case", tag);
if (correlationId is not null)
{
request.Headers.Add(CorrelationIdMiddleware.HeaderName, correlationId);
}
HttpResponseMessage response = await client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
bool echoed = response.Headers.Contains(CorrelationIdMiddleware.HeaderName);
statuses.Add(tag + " " + (int)response.StatusCode +
" cid " + (correlationId ?? (echoed ? "(generated)" : "(missing)")) +
" " + body);
}
sealed class RequestLog
{
private readonly List<string> lines = new List<string>();
public void Add(HttpContext context, string message)
{
string tag = context.Request.Headers["X-Case"].ToString();
lock (lines) { lines.Add(tag + " " + message); }
}
// Stable sort by case tag: requests may overlap, lines within one never do.
public string[] Ordered()
{
lock (lines) { return lines.OrderBy(l => l[0]).ToArray(); }
}
}
sealed class CorrelationIdMiddleware
{
public const string HeaderName = "X-Correlation-Id";
private readonly RequestDelegate next;
public CorrelationIdMiddleware(RequestDelegate next) => this.next = next;
// RequestLog is a singleton, but injecting per request works for any lifetime.
public async Task InvokeAsync(HttpContext context, RequestLog log)
{
bool supplied = context.Request.Headers.TryGetValue(HeaderName, out var incoming)
&& !string.IsNullOrWhiteSpace(incoming.ToString());
string id = supplied ? incoming.ToString() : Guid.NewGuid().ToString("N");
context.Items["CorrelationId"] = id;
context.Response.Headers[HeaderName] = id;
log.Add(context, "correlation " + (supplied ? "supplied " + id : "generated"));
await next(context);
}
}
sealed class ProblemMiddleware
{
private readonly RequestDelegate next;
public ProblemMiddleware(RequestDelegate next) => this.next = next;
public async Task InvokeAsync(HttpContext context, RequestLog log)
{
try
{
await next(context);
}
catch (Exception ex)
{
log.Add(context, "caught " + ex.GetType().Name);
if (context.Response.HasStarted)
{
// Headers are already on the wire; the only honest option is to fail.
log.Add(context, "abandoned response already started");
throw;
}
string id = context.Items["CorrelationId"] as string ?? "none";
context.Response.Clear(); // also wipes headers, so re-stamp the id
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.Headers[CorrelationIdMiddleware.HeaderName] = id;
await context.Response.WriteAsJsonAsync(new
{
title = "Unexpected error",
status = 500,
correlationId = id
});
}
}
}
sealed class AuditMiddleware
{
private readonly RequestDelegate next;
public AuditMiddleware(RequestDelegate next) => this.next = next;
public async Task InvokeAsync(HttpContext context, RequestLog log)
{
long started = Stopwatch.GetTimestamp();
try
{
await next(context);
}
finally
{
TimeSpan elapsed = Stopwatch.GetElapsedTime(started);
string speed = elapsed < TimeSpan.FromSeconds(5) ? "fast" : "slow";
log.Add(context, "completed " + context.Response.StatusCode + " (" + speed + ")");
}
}
}
Output:
1 correlation supplied trace-42
1 completed 200 (fast)
2 correlation generated
2 completed 200 (fast)
3 correlation supplied trace-77
3 caught InvalidOperationException
3 completed 500 (fast)
1 200 cid trace-42 {"ok":true}
2 200 cid (generated) {"ok":true}
3 500 cid trace-77 {"title":"Unexpected error","status":500,"correlationId":"trace-77"}
The registration order is the whole design. AuditMiddleware sits outside ProblemMiddleware, so by the time its finally block reads Response.StatusCode, the error handler has already decided on 500. Swap those two lines and case 3 logs completed 200 — the exception is still travelling up the stack when the audit runs, and the status code is untouched at its default. Dashboards built on that log would show a perfectly healthy service.
The HasStarted check is the difference between a useful error handler and one that throws a second exception on top of the first. If an endpoint streams half a payload and then fails, the status line and headers are long gone; Response.Clear would throw, and there is no way to retract what the client already received. Rethrowing at that point at least lets the server abort the connection so the client sees a truncated response rather than a plausible-looking one. Note also that Clear removes headers as well as the body, which is why the correlation id is stamped again afterwards.
The correlation id is written to two places on purpose. context.Items makes it available to anything further down the pipeline in the same request, including the error handler on the way back out, and the response header lets a caller quote the id in a support ticket. Case 2 shows the generated branch: no id was supplied, so one was created, and the client can see that a header came back without this program having to print a value that changes every run.
The fast / slow label stands in for what a real audit line records — elapsed milliseconds, the route, the user id — which cannot be printed in a lesson because it differs on every machine. In production that work belongs to ILogger with a scope carrying the correlation id, so every log line from the request is automatically tagged. One more thing this example deliberately leaves out: nothing here authenticates the caller. /ok and /boom are open to anyone who can reach the port, and the security module covers the components that close that gap.
Common Mistakes
- Registering components in the wrong order.
UseAuthorizationbeforeUseAuthenticationmeansctx.Useris always anonymous;UseCorsbeforeUseRoutingmeans the endpoint's CORS policy is invisible. The pipeline is nested, so position is behaviour, not style. - Forgetting to call
next. A component that neither callsnextnor writes a response returns200with an empty body, and the endpoint never runs. If short-circuiting is intended, set a status code and say why; if not, the missingawait next(ctx)is the bug. - Injecting scoped services into a convention-based middleware's constructor. The constructor runs once for the lifetime of the application, so a
DbContextcaptured there is shared by every concurrent request. Inject it intoInvokeAsyncinstead, or implementIMiddleware. - Writing to the response after it has started. Setting a status code or header once the first byte has been flushed throws
InvalidOperationException. CheckResponse.HasStarted, or move the work into anOnStartingcallback.
- Swallowing exceptions to keep the site up. A
catchthat logs nothing and returns200turns a hard failure into corrupted data and a silent dashboard. Catch to translate an exception into a response, never to pretend it did not happen. - Blocking inside the pipeline.
next(ctx).Wait()or.Resultoccupies a thread for the entire downstream request and can deadlock. Middleware is asynchronous from top to bottom; keep it that way withawait. - Reading the request body without enabling buffering. The body is a forward-only stream, so a component that reads it leaves nothing for the endpoint. Call
ctx.Request.EnableBuffering()first and rewind the stream, and accept the memory cost. - Putting per-endpoint logic in middleware. A component that starts with
if (ctx.Request.Path == "/orders")is an endpoint filter written in the wrong place. It runs for every request in the application to serve one route, and the condition rots the moment the route is renamed.
Best Practices
- Keep
Program.csreadable as a list of positions. The order ofUsecalls is documentation, so resist wrapping them in helper methods that hide which component runs first. - Put the exception boundary outermost and the audit or metrics component outside it, so the recorded status code is the one the client actually received.
- Move anything longer than a few lines into a class with
UseMiddleware<T>, and give it a companionUseXyzextension method so registration reads like the built-in components. - Inject scoped dependencies through
InvokeAsyncparameters, and treat every field on a convention-based middleware as shared mutable state that needs to be thread-safe or immutable. - Prefer
UseWhenover anifinside a component when a whole sub-pipeline should apply to a subset of requests; the intent is visible at registration. - Short-circuit early and cheaply. Rejecting a request before routing, authentication and database access is the least expensive work the server can do.
- Never write a raw exception message or stack trace to the response. Return a stable shape such as
ProblemDetailswith a correlation id, and keep the detail in the logs. - Test middleware in isolation by building a tiny pipeline around it rather than the whole application; a component that needs the full service graph to be testable is doing too much.
Practice Exercises
- Rate limit by header. Write a middleware class that allows at most three requests per
X-Client-Idvalue, returning429after that with aRetry-Afterheader. Store the counters in a singleton and make the access thread-safe. Prove with four in-process requests that the fourth is rejected while a different client id still succeeds. - Prove the ordering rule. Take the diagnostics stack from the example and move
AuditMiddlewareinsideProblemMiddleware. Send the same three requests and show that case 3 now records200instead of500, then explain in a comment which line of the pipeline made that happen. - Branch a sub-pipeline. Use
UseWhento apply a "maintenance mode" component only to requests whose path starts with/admin, returning503while the rest of the site keeps working. Then repeat withMapWhenand describe what changes about whether the main pipeline still runs. - Buffer and inspect a body. Write a component that logs the length of a JSON request body without breaking the endpoint that reads it afterwards. Enable buffering, read to the end, rewind to position zero, and verify with a
POSTthat the endpoint still deserialises its payload correctly.