ASP.NET Core 6+ 必须在 Program.cs 中显式配置 CORS,先通过 AddCors 注册命名策略(如 "AllowFrontend"),再在 UseRouting 后、MapControllers 前调用 UseCors("AllowFrontend");WithCredentials 与 WithOrigins 不能共用 "*",且前端 fetch 需设 credentials: "include" 才能协同生效。

ASP.NET Core 默认不启用跨域(CORS),直接在前端发请求会失败,不是前端代码问题,而是服务端没明确允许——必须在 Startup.cs 或 Program.cs 中显式配置策略。
如何在 ASP.NET Core 6+ 中启用 CORS(Program.cs 方式)
Core 6 起推荐在 Program.cs 中配置,顺序很关键:必须在 app.UseRouting() 之后、app.UseEndpoints()(或 app.MapControllers())之前调用 app.UseCors()。
常见错误是把 app.UseCors() 放在 app.UseAuthentication() 之后却忘了它依赖路由中间件,导致策略不生效。
- 先注册策略:在
builder.Services.AddCors()里定义命名策略,比如"AllowFrontend" - 再启用中间件:在
app链中调用app.UseCors("AllowFrontend") - 不要在控制器上加
[EnableCors]同时又全局UseCors,容易策略冲突
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.WithOrigins("http://localhost:5173") // 前端地址,不能写 * + credentials
.AllowAnyMethod()
.AllowAnyHeader()
.WithCredentials(); // 若前端带 cookie,此项必须开,且 WithOrigins 不能为 *
});
});
<p>var app = builder.Build();
app.UseRouting();
app.UseCors("AllowFrontend"); // ⚠️位置不能错
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();</p>
WithOrigins 为什么不能和 WithCredentials 一起用 "*"
浏览器规范强制要求:只要响应头包含 Access-Control-Allow-Credentials: true(即启用了 WithCredentials()),Access-Control-Allow-Origin 就不能是通配符 *,否则请求被直接拦截,控制台报错 The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'。
- 开发时可写具体地址,如
"http://localhost:5173"或"https://myapp.com" - 若需多域名,用
.WithOrigins("https://a.com", "https://b.com"),不能拼字符串 - 生产环境避免用
.SetIsOriginAllowed(_ => true)绕过——这等于手动实现不安全的*,且不被主流浏览器信任
前端 fetch 带 cookie 时后端必须同步满足三个条件
只配后端 CORS 策略不够,前端 fetch 发请求也得配合,否则预检(OPTIONS)可能失败,或凭据不发送。
- 前端请求必须显式设
credentials: "include" - 后端策略必须含
.WithCredentials() - 后端
WithOrigins必须指定确切源,不能是"*"
漏任一环,Chrome 控制台都会显示 CORS 错误,但具体提示可能误导你去查服务端日志——其实问题出在前后端配合缺失。
// 前端示例(Vite/React)
fetch("/api/values", {
method: "POST",
credentials: "include", // ⚠️缺了这句,后端即使开了 WithCredentials 也收不到 cookie
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ x: 1 })
});
CORS 不是“开个开关”就完事的机制,它是浏览器、前端请求配置、后端策略三者严格对齐的结果。最容易忽略的是 WithCredentials 和 WithOrigins 的互斥约束,以及 UseCors 在中间件管道里的精确位置。











