ASP.NET Core: how do I configure CORS for my React frontend?
posée 4 months ago633 vuesen
My React app on http://localhost:5173 gets blocked by CORS policy when calling my ASP.NET Core API on https://localhost:7001.
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.
1 réponse
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é.
Sign in and verify your email to post an answer.