What is the middleware ordering rule, and what breaks if you get it wrong?

ASP.NET Core Middleware Intermediate 2–3 Yrs3–5 Yrs Debugging 1 min read

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.

  • UseAuthorization before UseRouting → authorization doesn't know which endpoint it's protecting, so endpoint-specific policies don't work.
  • UseAuthentication after UseAuthorization → User isn't populated when authorization runs → everything is treated as anonymous.
  • UseCors after the endpoint → CORS headers aren't added.
  • UseExceptionHandler not first → an exception in earlier middleware isn't caught.
  • UseStaticFiles after routing/auth → static assets go through auth unnecessarily (or get blocked).