middleware-and-pipeline-orderlisted
Install: claude install-skill Sarmkadan/dotnet-senior-skills
# Middleware and Pipeline Order
## Order is the contract
Middleware runs in registration order on the way in, reverse on the way out. Most pipeline bugs are ordering bugs, and they fail silently - a misplaced middleware doesn't throw, it just doesn't apply. The canonical order:
```csharp
app.UseExceptionHandler(); // first: catches everything below
app.UseHsts(); // prod only
app.UseHttpsRedirection();
app.UseStaticFiles(); // before auth deliberately - or after, if files need auth (decide!)
app.UseRouting();
app.UseCors(); // after routing, before auth
app.UseAuthentication(); // WHO you are
app.UseAuthorization(); // WHAT you may do - always after authentication
app.MapControllers();
```
Review flags with their failure modes:
- `UseAuthorization` before `UseAuthentication`: authorization evaluates an anonymous principal - `[Authorize]` returns 401 for valid tokens, or worse, policies keyed on claims all fail open/closed confusingly.
- `UseCors` after `UseAuthentication`: preflight OPTIONS requests (which carry no credentials) hit auth and die with 401 - the browser reports it as a CORS error and someone "fixes" it by allowing anonymous.
- `UseExceptionHandler` anywhere but first: exceptions from middleware above it escape as raw 500s with no ProblemDetails and no logging.
- `UseStaticFiles` placement is a decision, not a default: before auth means every file is public - fine for CSS, an incident for `