Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

ASP.NET Core has CORS set up but the browser still blocks the request

ErrorAccess to fetch at 'https://localhost:5001/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Short answer

ASP.NET Core only adds CORS headers when a policy matches the request. Send the preflight yourself with curl first. Then check that UseCors sits after UseRouting and before UseAuthorization, that the policy is named in UseCors or set as default, and that the origin, headers and credentials fit what the browser sends.

  • Applies to ASP.NET Core 8, ASP.NET Core 9, ASP.NET Core 10
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Send the preflight by hand with an Origin that differs from the API's own host (without it, no CORS headers are returned at all). A 204 with Access-Control-Allow-Origin means the policy matched. A 204 with no Access-Control headers means the policy denied the preflight. A different status such as 401, 404 or 500 means something else answered first, so start with the middleware order.

    curl -i -X OPTIONS https://localhost:5001/api/items \
      -H "Origin: http://localhost:5173" \
      -H "Access-Control-Request-Method: POST" \
      -H "Access-Control-Request-Headers: content-type"
  2. 2Match what you see, then jump to its fix

    1. 1The preflight answer carries no Access-Control headers although AddCors and a policy existUseCors is in the wrong place in the pipelineFix
    2. 2AddPolicy("Frontend", ...) is in the code, yet no CORS header is ever sentA named policy exists but UseCors() is called without its nameFix
    3. 3The preflight returns 204 with no Access-Control-Allow-Origin, and the origin in your policy ends with a slash or differs in scheme or portThe allowed origin is written differently from the one the browser sendsFix
    4. 4The preflight returns 204 with no CORS headers, and Access-Control-Request-Headers in it lists a header such as authorization that your policy lacksWithHeaders or WithMethods does not include what the browser asks forFix
    5. 5The client uses credentials: 'include' (cookies), and the policy calls AllowAnyOrigin together with AllowCredentialsCredentials are sent but the policy allows any originFix
    6. 6ERR_INVALID_REDIRECT on the CORS preflight request, and the client calls an http:// URLHTTP to HTTPS redirection breaks the preflightFix

What does the error look like?

  • Access to fetch at 'https://localhost:5001/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Reason: CORS request did not succeed)
  • ERR_INVALID_REDIRECT on the CORS preflight request

Cause 1 of 6

UseCors is in the wrong place in the pipeline

1Check

Middleware runs in the order you add it. The CORS middleware has to come after UseRouting and before UseAuthorization, and before UseResponseCaching when you use it. Print the order in Program.cs.

grep -n "UseRouting\|UseCors\|UseAuthorization\|UseAuthentication\|UseResponseCaching\|UseStaticFiles\|MapControllers" Program.cs

2Fix

Move UseCors between UseRouting and UseAuthorization. If a script fetches static files from another site, call UseCors before UseStaticFiles too.

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors("Frontend");

app.UseAuthorization();
app.MapControllers();

3Verify

Run the preflight from the first step again; the Access-Control-Allow-Origin header should now be present.

curl -i -X OPTIONS https://localhost:5001/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST"

Confirmed by learn.microsoft.com

Did this fix it?

Cause 2 of 6

A named policy exists but UseCors() is called without its name

1Check

A bare app.UseCors() applies only the default policy. If you registered a named policy and never added a default, nothing is enabled. Look for how the policy is registered and how it is used.

grep -n "AddPolicy\|AddDefaultPolicy\|UseCors\|EnableCors\|RequireCors" Program.cs

2Fix

Pass the policy name to UseCors, or register the policy with AddDefaultPolicy. Pick one style: the docs recommend against mixing the [EnableCors] attribute with middleware in the same app.

builder.Services.AddCors(options =>
{
    options.AddPolicy("Frontend", policy =>
        policy.WithOrigins("http://localhost:5173")
              .AllowAnyHeader()
              .AllowAnyMethod());
});

// ...
app.UseCors("Frontend");

3Verify

Repeat the preflight. The response should list your origin in Access-Control-Allow-Origin.

curl -is -X OPTIONS https://localhost:5001/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: GET" | grep -i access-control

Confirmed by learn.microsoft.com

Did this fix it?

Cause 3 of 6

The allowed origin is written differently from the one the browser sends

1Check

An origin is scheme, host and port, with no path. A trailing slash in WithOrigins makes the comparison fail and no header is returned. http and https, or :5173 and :3000, are different origins.

grep -n "WithOrigins" Program.cs

2Fix

Write the origin exactly as the browser shows it in the Origin request header. For all subdomains of one domain, use a wildcard origin together with SetIsOriginAllowedToAllowWildcardSubdomains.

policy.WithOrigins("http://localhost:5173", "https://app.example.com");

// every subdomain of example.com
policy.WithOrigins("https://*.example.com")
      .SetIsOriginAllowedToAllowWildcardSubdomains();

3Verify

Send the preflight with the exact origin; the header should echo it back.

curl -is -X OPTIONS https://localhost:5001/api/items -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: GET" | grep -i allow-origin

Confirmed by learn.microsoft.com

Did this fix it?

Cause 4 of 6

WithHeaders or WithMethods does not include what the browser asks for

1Check

With WithHeaders, the policy matches only when the headers in Access-Control-Request-Headers exactly match the list. One extra header, for example Authorization or a custom one, makes the whole preflight fail. Compare both lists.

curl -i -X OPTIONS https://localhost:5001/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: PUT" -H "Access-Control-Request-Headers: content-type,authorization"

2Fix

Add every header and method the client really sends, or call AllowAnyHeader and AllowAnyMethod while you are developing.

using Microsoft.Net.Http.Headers;

policy.WithOrigins("http://localhost:5173")
      .WithHeaders(HeaderNames.ContentType, HeaderNames.Authorization)
      .WithMethods("GET", "POST", "PUT", "DELETE");

3Verify

Run the same preflight; the response should now carry Access-Control-Allow-Headers and Access-Control-Allow-Methods.

curl -is -X OPTIONS https://localhost:5001/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: PUT" -H "Access-Control-Request-Headers: content-type,authorization" | grep -i access-control

Confirmed by learn.microsoft.com

Did this fix it?

Cause 5 of 6

Credentials are sent but the policy allows any origin

1Check

The CORS specification does not accept a wildcard origin on a credentialed request, and ASP.NET Core returns an invalid CORS response when AllowAnyOrigin and AllowCredentials are both set. Using SetIsOriginAllowed(_ => true) to get around it is just as unsafe.

grep -n "AllowAnyOrigin\|AllowCredentials\|SetIsOriginAllowed" Program.cs

2Fix

Name the real origins and keep AllowCredentials. The browser side has to opt in too.

policy.WithOrigins("https://app.example.com")
      .AllowCredentials();

// browser
fetch('https://api.example.com/api/me', { credentials: 'include' });

3Verify

The response should show a single origin (not *) and Access-Control-Allow-Credentials: true.

curl -is -X OPTIONS https://api.example.com/api/me -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: GET" | grep -i access-control

Confirmed by learn.microsoft.com

Did this fix it?

Cause 6 of 6

HTTP to HTTPS redirection breaks the preflight

1Check

A request to the HTTP endpoint is answered with a redirect by UseHttpsRedirection, and the ASP.NET Core docs list this as a cause of ERR_INVALID_REDIRECT on the preflight. Check the base URL the front end uses.

grep -rn "http://localhost\|UseHttpsRedirection" Program.cs appsettings*.json

2Fix

Point the client at the HTTPS URL. For an API project, you can also drop UseHttpsRedirection so plain HTTP requests are rejected rather than redirected.

// front end
const API = 'https://localhost:5001';

// Program.cs (API project): remove this line
// app.UseHttpsRedirection();

3Verify

The preflight now answers directly with 204 and no redirect.

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

Confirmed by learn.microsoft.com

Did this fix it?

How do I stop it coming back?

  • Keep one named CORS policy in Program.cs and use it with app.UseCors, not the attribute in some places and middleware in others.
  • Put the allowed origins in configuration per environment, written without a trailing slash.
  • Keep a curl preflight command in your repo notes and run it after any change to the middleware order.
  • Never combine AllowAnyOrigin with AllowCredentials; list the real origins.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

The browser blocks your API response: no Access-Control-Allow-Origin header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/orders. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The browser received the response but refused to hand it to your script, because it did not carry an Access-Control-Allow-Origin header naming the page's origin.

4 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.