In ASP.NET Core, middleware wraps every component registered after it, so moving a single registration line changes what a component can observe and which exceptions it can catch. The article traces a broken exception boundary in an order API and the routing, authentication and authorization dependencies behind it.
Key points
- Middleware runs inbound in registration order and unwinds the response in reverse order.
- A component can catch only exceptions thrown inside its own `next` call.
- Terminal middleware such as a maintenance gate can return 503 without calling `next`, skipping later components.
- A request log moved above a short-circuit never runs for those requests, silently losing records.
- Parameterless `UseExceptionHandler()` needs `AddProblemDetails()` or an error path, or startup fails.
- Changing the status code or headers after the response starts throws; set headers before `next` or via `OnStarting`.
Why it matters
This is a failure class most teams discover in production: moving a line in `Program.cs` still compiles and the happy-path tests still pass, while the error paths break silently. Components like the exception handler, request logging and correlation IDs are written assuming they wrap everything registered after them; when that assumption shifts, you get missing log entries and 500 responses with no body. Because `WebApplication` in .NET 8 and later inserts some middleware automatically, the mistake can be hidden rather than obvious, so pinning the order with integration tests is more reliable than reviewing it by eye. Also check the `AddProblemDetails()` requirement for parameterless `UseExceptionHandler()` and the missing body for HTML-only clients against your own error response contract.
Real-world use
- A multi-store order API that resolves the store from the `X-Store` header before the endpoint runs.
- A maintenance gate that returns 503 during maintenance alongside a request log expected to record every request.
- An error-handling setup returning `application/problem+json` to JSON clients but an empty 500 body to HTML-only clients.
This summary was generated by the agent from the original post on ASI Backbone Learning. The full text and all rights belong to its author and publisher. Go to original