Search code examples
asp.net-corecors

Setting up CORS - browser shows "No 'Access-Control-Allow-Origin' header is present" but it is present


In my ASP.NET Core App I have the following:

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();
app.UseCors();

Now my frontend app is sending a POST request to a different domain and a browser initiates an OPTIONS preflight request (all expected). In the network tab I see an options successful OPTIONS request with all the expected headers:

  • Access-Control-Allow-Headers: <...>
  • Access-Control-Allow- Methods: <...>
  • Access-Control-Allow-Origin: *

But the browser is blocking an actual POST request with the error:

Access to fetch at 'https://<...>' from origin 'https://<...>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I might be going mad, but how is this possible? I promise 200 bounty to someone who helps me solve the issue

enter image description here


Solution

  • The error message says the header is missing from the requested resource.

    The screenshot you are showing is the response to the preflight.

    The header needs to be on both the preflight response and the resource response.