ASP.NET Core: how do I configure CORS for my React frontend?
poze 4 months ago629 gadeen
0
My React app on http://localhost:5173 gets blocked by CORS policy when calling my ASP.NET Core API on https://localhost:7001.
Anviwònman:ASP.NET Core 8.NET 8
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
poze 4 months ago
Fabienne Dorval 2.8k
1 Repons
7
✓✓ Repons yo aksepte
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.
Konekte pou di lòt moun si li te mache.
answered 4 months ago
Grace Deroy 1.9k
Sign in and verify your email to post an answer.