.NET Core UseCors() does not add headers

The problem is that when using Bearer authentication (or any I would imagine), it adds a header “Authorization”, and the server will only give an okay if the setup allows for that header.

There’s two ways to solve the problem, and below is the only code needed. It goes in the Configure() method in Startup.cs in the Web API solution.

Method 1: Allow all headers

app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
                                .AllowAnyMethod()
                                .AllowAnyHeader());

Method 2: Allow specific headers

app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
                              .AllowAnyMethod()
                              .WithHeaders("authorization", "accept", "content-type", "origin"));

The extra headers are because, per the documentation:

Browsers are not entirely consistent in how they set Access-Control-Request-Headers. If you set headers to anything other than “*”, you should include at least “accept”, “content-type”, and “origin”, plus any custom headers that you want to support.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)