I’m running into an unexpected issue getting Cors to run on a minimal api project. I setup a test project and just used the template to get it up and running then added what I thought should get the Cors stuff to show up but I’m not having any luck.
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);
}
I then call this with:
curl -vkX 'GET' 'https://localhost:8005/weatherforecast' -H 'accept: application/json'
and get this:
< 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}]
(I did edit out the handshake info)
I would expect to see the cors header(s) in the headers, but as you can see. It’s not there. What am I missing?
Also not sure if this makes a difference, but I’m running from a docker container.
Bryan Brown is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.