我在让Cors在ASP.NET Core 8 Minimal API项目上运行时遇到了一个意外问题.我设置了一个测试项目,只是使用模板启动并运行它,然后添加了我认为应该让Cors内容显示的内容,但我没有任何运气.

var builder = WebApplication.CreateBuilder(args);
const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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 }
]

(我确实编辑了握手信息)

我希望在标题中看到cors标题,但正如您所看到的,它不在那里.我错过了什么?

也不确定这是否有影响,但我正在从Docker容器运行.

Update/Solution 确保您的来源地匹配. 在上面的例子中,我的起源是http://example.com,但在我的请求头中,我将其设置为http://mysite.example.com. 我看过了.有时,这是最简单的问题,也是最难看到的问题.

推荐答案

在实际的中间件管道中设置CORS策略名称可以解决问题:

const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
//..
//previous code omitted for brevity
app.UseHttpsRedirection();
app.UseCors(MyAllowSpecificOrigins);
//..
//following code omitted for brevity

回应标题:

* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
    * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
    * old SSL session ID is stale, removing
    < HTTP/2 200 
    < content-type: application/json; charset=utf-8
    < date: Sun, 28 Apr 2024 12:47:36 GMT
    < server: Kestrel
    < access-control-allow-origin: http://example.com
    < 

我建议在引入一些棘手的中间件时始终坚持官方documentation.

Csharp相关问答推荐

如何在C#中使用并行主义将数据表转换为动态对象

从C#重新启动Shell脚本时处理错误?

在C#c/await中,延迟长度是否会影响控制返回调用者?

需要多次输入的控制台应用程序

访问C#中的数据库字段时获取数据是收件箱错误-为什么?&有效,如果声明不有效

VB.Net的SON模式导致集合代码不工作

C# Json重新初始化动态类型

System. InvalidOperationException:无法将数据库中的字符串值i转换为映射的ItemType枚举中的任何值''''

如何将Kafka消息时间戳转换为C#中的日期和时间格式?

实体框架核心中的ComplexType和OwnsOne有什么不同?

Amazon SP-API确认发货不设置&Quot;递送服务

在此系统上已禁用获取正在运行的脚本.&在ASP.NET Core Web API中

由于POST中的应用程序/JWT,出现不支持的内容类型异常

在两个已具有一对多关系的表之间添加另一个一对多关系

为什么我的伺服电机不动,下面的代码?

如何正确处置所有动态控件?

如何将默认区域性更改为fr-FR而不是en-US?

如何在使用Google.Drive.apis.V3下载文件/文件夹之前压缩?

Visual Studio如何使用当前的框架?

仅在Blazor Web App中覆盖生产的基本路径(.NET8中的_Hosts.cshtml文件功能?)