Skip to content
Happy Programming Guide
Start learning
C#

CORS Not Working in ASP.NET Core

The policy is defined and the browser still blocks the request. Middleware order, the policy that was never applied, credentials with a wildcard, and error responses that skip the headers.

An office workspace with a computer

ASP.NET Core has good CORS support and five ways to configure it that look right and do nothing. The policy is defined but never applied; UseCors is in the wrong place in the pipeline; the origin has a trailing slash; credentials are combined with a wildcard; or the response that failed was an exception that bypassed the middleware. Each one produces the same browser error, so check them in this order.

The working setup#

CSHARP
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy("Frontend", policy => policy
        .WithOrigins("http://localhost:3000", "https://app.example.com")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials());
});

var app = builder.Build();

app.UseExceptionHandler();
app.UseCors("Frontend");           // before auth and before endpoints
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Compare yours with this line by line. The differences are the causes below.

Cause 1: the policy is defined but not applied#

AddCors registers policies; it does not apply them. Without UseCors("Frontend") or a default policy, nothing happens. Three ways to apply:

  • app.UseCors("Frontend") for the whole application.
  • options.AddDefaultPolicy(...) plus a bare app.UseCors().
  • Per endpoint: [EnableCors("Frontend")] on a controller, or .RequireCors("Frontend") on a minimal API route, with app.UseCors() still present.

A named policy referenced in an attribute must exist, or the request fails with an exception rather than a CORS error.

Cause 2: middleware order#

UseCors must come after UseRouting (which WebApplication adds for you) and before UseAuthentication, UseAuthorization and the endpoint mappings. The preflight OPTIONS request carries no credentials; if authentication runs first, it rejects the preflight with a 401, the browser never sends the real request, and the console reports CORS. Move UseCors up.

It also needs to be before UseResponseCaching and UseStaticFiles if those responses must carry CORS headers.

Cause 3: the origin does not match#

CSHARP
.WithOrigins("http://localhost:3000/")     // wrong: trailing slash never matches
.WithOrigins("localhost:3000")            // wrong: scheme is required
.WithOrigins("http://localhost:3000")     // right

An origin is scheme, host and port, exactly as the browser sends it in the Origin header, and nothing more. https and http are different origins; port 3000 and port 3001 are different origins. Read the Origin header from a failing request in the browser’s Network tab and paste it verbatim.

For a family of subdomains, SetIsOriginAllowedToAllowWildcardSubdomains() with WithOrigins("https://*.example.com") works; for dynamic rules, SetIsOriginAllowed(origin => ...).

Cause 4: credentials with a wildcard#

CSHARP
policy.AllowAnyOrigin().AllowCredentials();     // throws at startup, or is ignored by browsers

Browsers refuse a wildcard origin when the request includes cookies or an Authorization header, and ASP.NET Core refuses the combination when it can detect it. If the front end uses credentials: 'include', the policy needs explicit origins and AllowCredentials(). If it does not send credentials, drop AllowCredentials().

Cause 5: the failing response bypassed the middleware#

An unhandled exception, a 404 from routing, or a response written by a component earlier in the pipeline may not go through UseCors, so it has no CORS headers, and the browser reports a CORS error instead of the real status. Check the Network tab: if the blocked response is a 500 or 404, fix that first. Registering UseExceptionHandler before UseCors ensures error responses pass through CORS on the way out.

Cause 6: custom headers not allowed#

Output
Request header field x-api-key is not allowed by Access-Control-Allow-Headers

Add it: .WithHeaders("Content-Type", "Authorization", "X-Api-Key"), or .AllowAnyHeader(). Similarly, a client reading a custom response header needs .WithExposedHeaders("X-Total-Count"); without that, the header is present but JavaScript cannot see it.

Verifying without the browser#

Terminal
curl -i -X OPTIONS https://localhost:5001/api/items \
  -H "Origin: http://localhost:3000" \
  -H "Access-Control-Request-Method: GET"

A 204 with Access-Control-Allow-Origin: http://localhost:3000 in the headers means the server side is right. If the headers are missing here, no browser or front-end change will help; it is one of the causes above.

Development and production#

Origins differ between environments. Put them in configuration:

CSHARP
var origins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>() ?? [];
policy.WithOrigins(origins)...
JSON
{ "Cors": { "Origins": ["http://localhost:3000"] } }

Then appsettings.Production.json carries the real domain, and nobody has to remember to change code at deploy time.

Questions people ask#

Do I need CORS if the front end is served by the same ASP.NET Core app?

No. Same origin, no CORS. It is only needed when the browser page and the API are on different origins, such as a separate dev server.

Why does it work in Swagger and not from React?

Swagger UI is served from the API’s own origin. React on its dev server is a different origin.

Minimal APIs: where does the policy go?

Same AddCors and UseCors; apply per route with .RequireCors("Frontend") if you do not want it global.

SignalR?

Needs AllowCredentials() with explicit origins, because it uses cookies and WebSockets; a wildcard origin breaks the negotiation.

Where to go next#

ASP.NET Core error handling, including why order mattersRead next

Keep reading

C#

C# Reflection and Attributes

Reading type information at run time, writing custom attributes, and the performance cost — plus source generators as the modern alternative.

5 min read

C#

C# and ASP.NET Core

Building web applications and APIs with ASP.NET Core: minimal APIs, controllers, dependency injection, middleware, validation and configuration.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *