CORS in .NET 6.0 web api

Viewed 7155

I have a React app calling a .NET 6 Web API using Axios.

In the program.cs file, I have added builder.Services.AddCors and app.UseCors as below.

But I still get CORS error and 404 preflight.

The method used to works in .NET 5 Web Api.

Is there anything we need to set for .NET 6 Web Api ?

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
<removed>

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors();

// Add services to the container.
<removed>

// App settings
<removed>

<removed>

builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
    });

// AutoMapper
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

<removed>

// Firebase
<removed>

var app = builder.Build();

The CORS registration is

app.UseCors(x => x.AllowAnyHeader()
      .AllowAnyMethod()
      .WithOrigins("https://our-react-site.com"));

And the rest of the code

// Configure the HTTP request pipeline. 
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();
3 Answers

The CORS docs explain that UseCors middleware needs to be called in the correct order.

UseCors must be called in the correct order. For more information, see Middleware order. For example, UseCors must be called before UseResponseCaching when using UseResponseCaching.

The Middleware Order section shows that UseCors needs to be called after redirection and routing and before authentication and authorization.

enter image description here

In your code you'll have to call UseCors after UseHttpsRedirection and right before UseAuthentication :

app.UseHttpsRedirection();


app.UseCors(x => x.AllowAnyHeader()
      .AllowAnyMethod()
      .WithOrigins("https://our-react-site.com"));

app.UseAuthentication();

The documentation example shows this:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

Another difference is that the doc example creates at least one named policy and uses UseCors to apply this policy.

If you're using UseMiddleware, UseCors must be specified before it e.g.

var app = builder.Build();

app.UseCors(policy => policy.AllowAnyHeader()
                            .AllowAnyMethod()
                            .SetIsOriginAllowed(origin => true)
                            .AllowCredentials());

app.UseMiddleware<ApiKeyMiddleware>();

added this to my program.cs file in .NET 6.0 web api

app.UseCors(options => options.AllowAnyOrigin());
Related