ASP.NET Core 6+需手动注册CORS服务并正确配置中间件顺序:先调用builder.Services.AddCors(),再在UseRouting之后、MapControllers之前调用app.UseCors("MyPolicy");策略中禁用"*"与AllowCredentials()共用,开发用具体源如https://localhost:5173,生产用配置白名单。

ASP.NET Core 6+ 默认不启用 CORS,必须手动注册中间件
新项目里直接写 app.UseCors() 会报错“CORS middleware not found”,因为没注册服务。顺序也关键:必须在 app.UseRouting() 之后、app.UseEndpoints() 或 app.MapControllers() 之前调用。
- 先在
Program.cs顶部调用builder.Services.AddCors() - 再在
app链中调用app.UseCors("MyPolicy")(策略名要一致) - 如果用了
app.MapControllers(),UseCors必须在这之前,否则不生效
CORS 策略里别直接写 "*" 允许所有源(尤其带凭据时)
"*" 在允许 credentials: true 时会被浏览器拒绝,错误信息是 Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'。
- 开发环境可写具体地址,比如
https://localhost:5173(Vite 默认端口) - 生产环境建议用配置项或环境变量动态加载白名单,避免硬编码
- 若真需多源,用
WithOrigins()传字符串数组,不要拼接"*"
前端带 cookie 或 Authorization 头时,后端必须显式开启凭据支持
只要前端发请求时加了 credentials: "include" 或设置了 withCredentials = true,后端策略就必须同时满足两个条件:允许指定源(不能是 "*")、调用 AllowCredentials()。
- 策略定义里漏掉
.AllowCredentials()→ 浏览器静默丢弃响应 - 策略里写了
.AllowCredentials()但.WithOrigins("*")→ 启动时报错或预检失败 - 常见组合:
.WithOrigins("https://myapp.com").AllowCredentials()
OPTIONS 预检请求失败?检查是否被其他中间件拦截或重写
POST/PUT 带自定义头(如 X-Requested-With)或非简单 Content-Type(如 application/json)时,浏览器会先发 OPTIONS 请求。如果返回 404 或 405,说明没走到 CORS 中间件。
立即学习“前端免费学习笔记(深入)”;
- 确保没有
app.UseStaticFiles()或自定义路由提前终结了请求 - 检查是否有中间件(如认证、限流)在
UseCors之前抛出异常或跳过后续管道 - 用
curl -X OPTIONS -I http://localhost:5000/api/values手动验证响应头是否含Access-Control-Allow-Origin


















