var builder = WebApplication.CreateBuilder(args);// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();//此处1
builder.Services.AddCors(options =>
{options.AddPolicy("AllowSpecificOrigin",builder => builder.WithOrigins("http://localhost:5175") // 允许来自这个域名的请求.AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}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();//此处2
app.UseCors("AllowSpecificOrigin");app.Run();internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
安装 Microsoft.AspNetCore.Cors库
添加两处代码即可