8

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();
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
Law Hui Sheng
  • 315
  • 1
  • 2
  • 9

4 Answers4

14

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.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Thanks. Somehow the code works in local but doesn't work in live (hosted on IIS 10). Is there any setting on server / IIS that might cause this? Web.config file is the same as local. – Law Hui Sheng Dec 21 '21 at 03:03
  • 1
    https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core/53280377#53280377 Issue solved by allowing OPTIONS Verb – Law Hui Sheng Jan 03 '22 at 08:49
  • Order is very important. I had custom extensions to cleanup `Program.cs`. One of those was adding the `UseRouting` middleware before `UseHttpsRedirection` that I was unaware of. – Akshay Rajpaul Jul 22 '22 at 13:39
2

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>();
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
0

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

app.UseCors(options => options.AllowAnyOrigin());
Mikhail
  • 1
  • 3
-1

You might be blocking the OPTIONS http verb in IIS. Check the "HTTP Verbs" Tab in Request Filtering settings in your IIS. Remove the highlighted option as shown in the image from the link below.

IIS Request Filtering