What is the recommended standard order for common middleware in a typical ASP.NET Core Web API pipeline, and why?
Short answer
A commonly recommended order is: exception handling first (to catch errors from everything after it), HTTPS redirection, HSTS, static files (served early to bypass unnecessary processing), routing, CORS (must be after routing, before authorization), authentication…
Advertisement
AModel answer
A commonly recommended order is: exception handling first (to catch errors from everything after it), HTTPS redirection, HSTS, static files (served early to bypass unnecessary processing), routing, CORS (must be after routing, before authorization), authentication, authorization, custom business middleware, then endpoint mapping last. Each position reflects a dependency: authorization needs authentication's identity, CORS decisions need routing's matched endpoint metadata, and exception handling needs to wrap everything to catch downstream failures.
app.UseExceptionHandler("/error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("MyPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();Real-world example
A subtle production bug where CORS headers weren't applied correctly for certain error responses is traced to UseCors being registered before UseRouting instead of after, violating the documented recommended order.
Likely follow-ups
- What breaks specifically if CORS is registered before routing?
- Does this order change for minimal APIs versus MVC controllers?
Related topics