




ASP.NET Core 配置 CORS 需在Program.cs 中按顺序注册服务(AddCors)并启用中间件(UseCors),策略名须一致;推荐具名策略,生产环境应避免 AllowAnyOrigin() 与凭据共用。
ASP.NET Core 配置跨域(CORS)很简单,关键是按顺序在 Program.cs 中注册服务并启用中间件,且策略名称要前后一致。
在 Program.cs 的顶部(var builder = WebApplication.CreateBuilder(args); 之后),添加 CORS 服务:
AddCors() 注册服务,支持链式配置策略builder.Services.AddCors(options =>
{
options.AddPolicy("MyAllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
在 var app = builder.Build(); 之后、app.Run(); 之前,调用 UseCors() 启用中间件:
UseRouting() 之后、UseAuthorization() 和 UseEndpoints() 之前AddPolicy() 中定义的一致app.UseRouting();
app.UseCors("MyAllowAll"); // 注意:这里必须匹配策略名
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
如果不想全局启用,可以只对特定控制器或 Action 启用 CORS:
[EnableCors("MyAllowAll")]
[ApiController]
[Route("api/[controller]")]
[EnableCors("MyAllowAll")]
public class ValuesController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new[] { "a", "b" });
}
开发时用 AllowAnyOrigin() 很方便,但上线前务必收紧:
AllowAnyOrigin() + AllowCredentials() 组合(浏览器会拒绝)WithOrigins("https://yourdomain.com")
WithHeaders("Content-Type", "X-Custom-Header")
基本上就这些。顺序、命名、位置三者对了,CORS 就能正常工作。