skip to content

Search

Fixing CORS Errors in .NET: UseCors() Order Matters

1 min read

CORS requests failed in a .NET app due to incorrect UseCors() middleware order. Here's how the request pipeline works and how to fix it.

The CORS error mentioned in Gotcha: Angular HttpInterceptor sees status: 0 on failure was caused by incorrect ordering of the UseCors() middleware in the .NET backend.

Here’s what I had:

app.UseAuthentication();
app.UseAuthorization();
app.UseCors();

This caused the browser to block the request with a CORS error because the CORS headers were being applied too late.

.NET enforces order-dependent middleware as part of the request processing pipeline, so the fix was to move UseCors() earlier:

+ app.UseCors();
  app.UseAuthentication();
  app.UseAuthorization();
- app.UseCors();

Now the CORS headers are set before anything that could short-circuit the pipeline or return an error.

I had to discover this via the browser console because it’s a runtime error. It’s the kind of thing you wish the compiler could warn you about.

More details:

TL;DR

In .NET, middleware order matters. Place app.UseCors() before UseAuthentication() and UseAuthorization() to ensure CORS headers are sent early enough to avoid browser-side errors.