Advertisement
Intermediate .NET, CORS & Cross-Origin Resource Sharing

Why must UseCors be positioned after UseRouting but before UseAuthorization in the ASP.NET Core middleware pipeline?

Short answer

UseCors needs routing to have already matched the request to determine which endpoint's specific CORS policy (if using [EnableCors] per-endpoint) applies, so it must come after UseRouting.

Save .NET mock interview
Advertisement
AModel answer
UseCors needs routing to have already matched the request to determine which endpoint's specific CORS policy (if using [EnableCors] per-endpoint) applies, so it must come after UseRouting. It must come before UseAuthorization because a CORS preflight OPTIONS request has no authentication credentials and would otherwise be incorrectly rejected by authorization checks before CORS even gets a chance to respond to it -- placing CORS first ensures preflight requests are handled correctly regardless of the endpoint's authorization requirements.
app.UseRouting();        // must be first: matches endpoint metadata
app.UseCors("MyPolicy");  // must be here: needs endpoint match, but before auth
app.UseAuthentication();
app.UseAuthorization();   // preflight OPTIONS requests never reach this far incorrectly
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