You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Web API缺失Access-Control-Allow-Origin头致CORS错误

问题:ASP.NET Core 6 Web API CORS配置不生效,响应头缺失Access-Control-Allow-Origin

依照微软文档在ASP.NET Core 6 Web API中启用了CORS,但API响应中未出现预期的Access-Control-Allow-Origin头。使用Angular客户端调用该API时,Chrome和Firefox均触发CORS错误。已尝试多个相关解决方案仍未解决,以下是我的代码配置:

Program.cs 代码

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "EnableCORS", builder =>
    {
        builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .SetIsOriginAllowed((host) => true);
    });

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppConfig:Token").Value)),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseCors("EnableCORS");
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Angular项目Web.config配置

<?xml version="1.0" encoding="UTF-8"?>
    <configuration>
    <system.webServer>        
    <security>
        <requestFiltering>
            <fileExtensions allowUnlisted="true" />
        </requestFiltering>
    </security>             
    <httpProtocol>
        <customHeaders>
        <remove name="X-Frame-Options" />
        <remove name="Content-Security-Policy" />
        </customHeaders>
    </httpProtocol>             
    </system.webServer>
</configuration>
解决办法
  • 修正中间件顺序:在ASP.NET Core 6的最小API模型中,显式添加路由中间件能确保CORS逻辑正确触发。修改请求管道配置:

    //app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting(); // 新增路由中间件
    app.UseCors("EnableCORS");
    app.UseAuthentication();
    app.UseAuthorization();
    
    // 替换原MapControllers为显式端点配置
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    
  • 移除冗余CORS配置:AllowAnyOrigin()已允许所有来源,和SetIsOriginAllowed((host) => true)存在逻辑冲突,移除后者:

    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: "EnableCORS", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });
    
  • 检查IIS头拦截:IIS可能覆盖ASP.NET Core返回的CORS头,可在Angular项目的web.config中手动添加CORS头测试:

    <httpProtocol>
        <customHeaders>
            <remove name="X-Frame-Options" />
            <remove name="Content-Security-Policy" />
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
            <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
        </customHeaders>
    </httpProtocol>
    
  • 处理认证环节的CORS头缺失:若请求因认证失败提前返回响应,CORS头不会被添加。可在JWT配置中添加事件处理,确保认证失败时也返回CORS头:

    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppConfig:Token").Value)),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                return Task.CompletedTask;
            }
        };
    });
    
  • 指定具体来源(针对带Credentials的请求):若Angular请求包含Cookie等凭证,AllowAnyOrigin()会失效,需指定具体来源:

    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: "EnableCORS", builder =>
        {
            builder.WithOrigins("http://localhost:4200") // 替换为实际Angular域名
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials();
        });
    });
    

    同时Angular客户端需设置withCredentials: true。

内容的提问来源于stack exchange,提问作者Bing Code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:35:54