What is the middleware ordering rule, and what breaks if you get it wrong?
Quick Answer
Middleware runs in the order you add it, and the response unwinds in reverse. The rules that matter: exception handling first, then HSTS/HTTPS redirection, then static files, then UseRouting, then UseCors, then UseAuthentication, then UseAuthorization, then endpoints. Getting it wrong causes subtle bugs — auth that doesn't apply, CORS headers missing on errors, etc.
Middleware executes top to bottom as you register it, and the response comes back through it in reverse. The ordering that trips people up: authentication has to come before authorization, or the user is never populated and everything looks anonymous. Routing has to come before authorization, or endpoint-specific policies don't apply. Exception handling goes first so it wraps everything below. And CORS has to be in the right place or the headers don't get added, especially on error responses. If something “works but the policy isn't being enforced,” middleware order is the first thing I check.
UseAuthorizationbeforeUseRouting→ authorization doesn't know which endpoint it's protecting, so endpoint-specific policies don't work.UseAuthenticationafterUseAuthorization→Userisn't populated when authorization runs → everything is treated as anonymous.UseCorsafter the endpoint → CORS headers aren't added.UseExceptionHandlernot first → an exception in earlier middleware isn't caught.UseStaticFilesafter routing/auth → static assets go through auth unnecessarily (or get blocked).