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

ASP.NET Core 8 Minimal API中CORS Headers不显示问题排查

ASP.NET Core 8 Minimal API CORS配置后响应头无预期字段问题

问题描述

在ASP.NET Core 8 Minimal API项目中,通过模板创建项目并配置CORS后,发起跨域请求时响应头未出现预期的CORS相关字段。项目运行在Docker容器中。

配置代码

var builder = WebApplication.CreateBuilder(args);
const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://example.com",
                "http://www.contoso.com");
        });
});

var app = builder.Build();

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

app.UseHttpsRedirection();

app.UseCors();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
    {
        var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                (
                    DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    Random.Shared.Next(-20, 55),
                    summaries[Random.Shared.Next(summaries.Length)]
                ))
            .ToArray();
        return forecast;
    })
    .WithName("GetWeatherForecast")
    .WithOpenApi();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) {
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

请求命令

curl -vkX 'GET'   'https://localhost:8005/weatherforecast'   -H 'accept: application/json' -H "Access-Control-Request-Method: GET"   -H "Origin: http://mysite.example.com"

响应结果

HTTP/2 200   
content-type: application/json; charset=utf-8  
date: Sat, 27 Apr 2024 17:45:49 GMT  
server: Kestrel  

Connection #0 to host localhost left intact
[
    { "date": "2024-04-28", "temperatureC": 25,"summary": "Balmy", "temperatureF": 76 },
    { "date": "2024-04-29", "temperatureC": 37,"summary": "Mild", "temperatureF": 98 },
    { "date": "2024-04-30", "temperatureC": 9,"summary": "Cool", "temperatureF": 48 },
    { "date": "2024-05-01", "temperatureC": 10,"summary": "Chilly", "temperatureF": 49 },
    { "date": "2024-05-02", "temperatureC": 17,"summary": "Mild", "temperatureF": 62 }
]

解决方案

请求携带的Origin(http://mysite.example.com)与CORS配置中允许的Origin(http://example.com、http://www.contoso.com)不匹配,将请求的Origin修改为配置内的地址,即可使CORS响应头正常出现。

内容的提问来源于stack exchange,提问作者Bryan Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:22:16