我在让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. 我看过了.有时,这是最简单的问题,也是最难看到的问题.