ASP.NET Core: how do I configure CORS for my React frontend?

asked 4 months ago634 viewsen

0

My React app on http://localhost:5173 gets blocked by CORS policy when calling my ASP.NET Core API on https://localhost:7001.

Environment:ASP.NET Core 8.NET 8

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 4 months ago

1 Answer

7
✓
✓ Accepted answer

Register a named policy and apply it before auth and endpoints:

builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p
    .WithOrigins("http://localhost:5173", "https://app.example.ht")
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials()));

var app = builder.Build();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Notes: - AllowCredentials() (for cookies) can't be combined with AllowAnyOrigin(). List the origins explicitly. - Put the origins in configuration (appsettings.{Environment}.json) so production doesn't allow localhost. - In development, a Vite proxy (server.proxy in vite.config) avoids CORS entirely.

Sign in to tell others whether this worked.

answered 4 months ago

Sign in and verify your email to post an answer.