Home > Net >  CORS - Why do I get multiple values in my Access-Control-Allow-Origin header
CORS - Why do I get multiple values in my Access-Control-Allow-Origin header

Time:11-11

I have an API where one endpoint is being called from a public facing website. Whenever the website calls the API, I get the following error

Access to fetch at '{{API Endpoint}}' from origin 'https://{{Website Domain}}' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://{{Website Domain}}, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My API's Program.cs appears to be setup correctly

builder.Services.AddCors(options =>
{
    options.AddPolicy(
        "CMSPolicy",
        policy =>
        {
            policy.WithOrigins("https://{{Website Domain}})
                .WithHeaders(HeaderNames.ContentType, "application/json");
        });
});



app.UseCors();

and my controller has the [EnableCors("CMSPolicy")] annotation on the endpoint.

This has previously worked, but a change has been made where the API now imports a bespoke NuGet package which itself contains some controllers. These imported controllers aren't related to this affected one, and the bespoke package doesn't contain any code I can see that references CORS, but I'm including this information for completeness in case it is relevant.

If I remove the EnableCors annotation from my endpoint then the call from the website works, but that is with an Access-Control-Allow-Origin header value of '*' and I would prefer the security of this header just being my website domain

CodePudding user response:

I found the problem, it turned out that part of the project setup (in this case the setup of a Docker image for the API) was inserting an "access-control-allow-origin: *" header into every response from the API, and then the EnableCors attribute just adds another one instead of replacing the existing header, hence the issue.

CodePudding user response:

I did a test and there is no problem, you can refer to it:

Program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "CMSPolicy",
                      policy =>
                      {
                          policy.WithOrigins("https://localhost:7010")
                            .WithHeaders(HeaderNames.ContentType, "application/json");
                      });
});
//...
app.UseCors();

Controller:

[EnableCors("CMSPolicy")]
public class WeatherForecastController : ControllerBase {}

Result:

enter image description here

Make sure your opening/closing quotes match and app.UseCors(); is in the correct place. The call to UseCors must be placed after UseRouting, but before UseAuthorization.

For more details.please refer to CORS with named policy and middleware.

  • Related