我在让 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'
并得到这个:
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 容器运行的。
尝试添加 RequireCors(MyAllowSpecificOrigins)
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()
.RequireCors(MyAllowSpecificOrigins);