Advertisement
Intermediate ASP.NET Core, CORS (Cross-Origin Resource Sharing)

Where must UseCors be positioned in the middleware pipeline relative to UseRouting and UseAuthorization, and why does this order matter?

Short answer

UseCors must come after UseRouting (since it may need endpoint-specific policy metadata from routing) but before UseAuthorization (since a CORS preflight OPTIONS request carries no authentication credentials and would otherwise be incorrectly rejected by authorization checks…

Save ASP.NET Core mock interview
Advertisement
AModel answer
UseCors must come after UseRouting (since it may need endpoint-specific policy metadata from routing) but before UseAuthorization (since a CORS preflight OPTIONS request carries no authentication credentials and would otherwise be incorrectly rejected by authorization checks before CORS ever gets to respond) -- misordering this causes confusing failures where legitimate cross-origin requests to protected endpoints fail with CORS errors instead of proper authorization behavior.
app.UseRouting();
app.UseCors("MyPolicy");   // after routing, before authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
Real-world example
A production bug where cross-origin requests to an [Authorize]-protected endpoint always failed with CORS errors (not auth errors) was traced to UseCors being registered after UseAuthorization instead of before, causing preflight requests to be rejected by the authorization check first.
Likely follow-ups
  • What HTTP status does a rejected preflight request typically show in browser dev tools?
  • How does this ordering interact with endpoint-specific [EnableCors] attributes?
Related topics