12. The middleware pipeline
Sections
Reading settings
Natural voice recorded for this course, the same in every browser.
No voice for this language in this browser.
More voices
Code and English terms
Off: the page’s voice reads everything, with no pause between two voices.
No voice for this language in this browser.
More voices
More voices: Microsoft Edge has natural online voices, and Windows (Settings › Time & language › Speech), macOS and Android install others.
ASP.NET Core middleware is nested control flow. Code before next runs on the way in; code after next runs on the way out. Registration order is therefore observable behavior.
The onion is executable
Section titled “The onion is executable”The lesson registers an outer middleware, a gate and one endpoint. The successful request produces:
GET /ok: 200; outer:before -> endpoint -> outer:afterThe gate deliberately short-circuits /blocked:
GET /blocked: 429; outer:before -> gate:short-circuit -> outer:afterThe endpoint is absent because the gate did not call next. The outer middleware still completes its response path.
Ordering rules with consequences
Section titled “Ordering rules with consequences”- exception handling must wrap code whose exceptions it converts;
- forwarded headers must run before code that reads scheme, host or client IP;
- routing selects an endpoint before authorization evaluates endpoint metadata;
- authentication establishes a principal before authorization checks it;
- response compression and caching must be placed according to which representation they store or transform;
- terminal
Runmiddleware ends the branch.
Map branches by path; MapWhen branches by a predicate; endpoint routing dispatches endpoint metadata. A branch is not a new process or trust boundary.
Run the proof
Section titled “Run the proof”dotnet run --project code/csharp-advanced/Advanced -c Release -- l12The checked transcript is expected/l12.txt.
Exercises
Section titled “Exercises”- Put exception handling after an endpoint that throws. Explain why it cannot convert that exception.
- Add a correlation-id middleware and decide whether a client-supplied ID is trusted, replaced or namespaced.
- Add a
Map("/admin")branch and prove that authorization still runs inside it.
Solutions
- Middleware only wraps components registered after it. Move the handler earlier and keep the original exception in logs while returning a stable problem response.
- Validate length and character set, preserve the inbound value only as untrusted baggage, and generate the server correlation ID used for logs and responses.
- Register authentication/authorization in the relevant branch or use endpoint routing with authorization metadata. A path branch alone grants no authority.