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

posée 4 months ago633 vuesen

0

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

Environnement :ASP.NET Core 8.NET 8

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 4 months ago

1 réponse

7
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.