Asp.net core 跨域配置
🌐 一、什么是 CORS?
CORS(Cross-Origin Resource Sharing,跨域资源共享) 是一种由浏览器强制执行的安全机制,用于控制 一个源(Origin)的网页是否可以访问另一个源的资源。
- 同源策略(Same-Origin Policy):浏览器默认禁止前端 JavaScript 向不同源的服务器发起请求。
- CORS 是标准解决方案:后端通过响应头告诉浏览器:“我允许哪些前端域名来访问我”。
✅ 举例:
前端:http://localhost:8080
后端:https://api.example.com
→ 这是跨域请求,必须配置 CORS,否则浏览器会拦截响应!
⚙️ 二、ASP.NET Core 中 CORS 的工作流程
- 前端发起跨域请求(如
fetch("https://api.example.com/data")
) - 浏览器自动添加
Origin
请求头:Origin: http://localhost:8080
- ASP.NET Core 接收到请求,CORS 中间件检查:
- 该
Origin
是否在允许列表中? - 是否允许携带凭据(Cookies)?
- 是否允许该 HTTP 方法和请求头?
- 该
- 如果允许,返回 CORS 响应头:
Access-Control-Allow-Origin: http://localhost:8080 Access-Control-Allow-Credentials: true
- 浏览器验证响应头,决定是否将数据暴露给前端 JavaScript。
🛠️ 三、CORS 配置步骤(三步走)
第 1 步:注册 CORS 服务(在 Program.cs
)
var builder = WebApplication.CreateBuilder(args);// 注册 CORS 服务
builder.Services.AddCors(options =>
{// 方式1:定义默认策略(推荐)options.AddDefaultPolicy(policy =>{policy.WithOrigins("http://localhost:8080", "https://deali.cn").AllowAnyHeader().AllowAnyMethod();});// 方式2:定义命名策略(可选)options.AddPolicy("MyPolicy", policy =>{policy.WithOrigins("https://trusted-site.com").AllowAnyHeader().WithMethods("GET", "POST");});
});
第 2 步:启用 CORS 中间件(在请求管道中)
var app = builder.Build();// 必须在 UseRouting() 之后,UseAuthorization() 之前
app.UseRouting();app.UseCors(); // ← 使用默认策略
// 或 app.UseCors("MyPolicy"); // ← 使用命名策略app.UseAuthentication();
app.UseAuthorization();app.MapControllers();
app.Run();
第 3 步:确保前端正确发起请求(前端代码示例)
// Vue / React / 原生 JS
fetch("https://your-api.com/api/values", {method: "GET",credentials: "include", // 如果需要携带 Cookieheaders: {"Content-Type": "application/json"}
})
.then(res => res.json())
.then(data => console.log(data));
📚 四、常用配置方法详解
方法 | 作用 | 注意事项 |
---|---|---|
.WithOrigins("http://a.com", "https://b.com") | 指定允许的前端源 | 必须完整(协议+域名+端口) |
.AllowAnyOrigin() | 允许任意源 | ❌ 不能与 .AllowCredentials() 同时使用 |
.AllowCredentials() | 允许携带 Cookie/认证头 | 必须配合 WithOrigins ,不能用 AllowAnyOrigin |
.AllowAnyHeader() | 允许任意请求头 | 如 Authorization , X-Custom |
.WithHeaders("X-API-Key") | 仅允许指定请求头 | |
.AllowAnyMethod() | 允许任意 HTTP 方法 | GET/POST/PUT/DELETE 等 |
.WithMethods("GET", "POST") | 仅允许指定方法 | |
.SetIsOriginAllowed(_ => true) | 动态允许所有源(慎用) | 可用于调试,生产环境禁用 |
🧪 五、完整配置示例
示例 1:开发环境(允许 localhost 多端口 + 凭据)
builder.Services.AddCors(options =>
{options.AddDefaultPolicy(policy =>{policy.AllowCredentials().WithOrigins("http://localhost:3000","http://localhost:8080","http://localhost:5173" // Vite 默认端口).AllowAnyHeader().AllowAnyMethod();});
});
示例 2:生产环境(明确指定前端域名)
builder.Services.AddCors(options =>
{options.AddDefaultPolicy(policy =>{policy.WithOrigins("https://deali.cn", "https://www.deali.cn").AllowAnyHeader().WithMethods("GET", "POST", "PUT", "DELETE");// 不允许凭据(更安全)});
});
示例 3:通过配置文件管理 Origins(推荐!)
// appsettings.json
{"AllowedOrigins": ["http://localhost:8080","https://deali.cn"]
}
// Program.cs
var allowedOrigins = builder.Configuration.GetSection("AllowedOrigins").Get<string[]>();builder.Services.AddCors(options =>
{options.AddDefaultPolicy(policy =>{policy.WithOrigins(allowedOrigins).AllowAnyHeader().AllowAnyMethod();});
});
⚠️ 六、常见错误与解决方案
❌ 错误 1:AllowAnyOrigin()
+ AllowCredentials()
冲突
policy.AllowAnyOrigin(); // ❌
policy.AllowCredentials(); // ❌ 冲突!
浏览器报错:
The value of the 'Access-Control-Allow-Origin' header must not be '*' when credentials are included.
✅ 解决:改用 WithOrigins()
明确指定源。
❌ 错误 2:忘记调用 app.UseCors()
注册了服务但没启用中间件 → CORS 不生效!
✅ 解决:确保在管道中调用 app.UseCors();
❌ 错误 3:Origin 不匹配
- 配置了
http://localhost:8080
,但前端用http://127.0.0.1:8080
→ ❌ - 配置了
https://deali.cn
,但用户访问http://deali.cn
→ ❌
✅ 解决:确保协议、域名、端口完全一致。
❌ 错误 4:预检请求(Preflight)失败
对于复杂请求(如带自定义头、非简单方法),浏览器会先发 OPTIONS
请求。
✅ ASP.NET Core CORS 中间件自动处理 OPTIONS,无需额外代码。
🔒 七、安全建议
- 永远不要在生产环境使用
AllowAnyOrigin()
+AllowCredentials()
- 明确列出可信前端域名
- 避免使用通配符子域名(如
*.example.com
),除非必要 - 敏感 API 可结合 CORS + 身份认证(JWT/Cookie)双重保护
- 定期审查允许的 Origins 列表
📌 八、总结
关键点 | 说明 |
---|---|
CORS 保护的是后端 API | 防止恶意网站盗用你的接口 |
配置的是“前端源” | 不是后端部署地址 |
三步配置 | AddCors() → UseCors() → 前端正确调用 |
凭据 + 任意源 = 禁止 | 必须用 WithOrigins() |
推荐通过配置文件管理 Origins | 便于多环境部署 |
🔗 官方文档参考
- Enable Cross-Origin Requests (CORS) in ASP.NET Core