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();