问题
以 asp.net core 6 为后端,使用 ReactJS 或者其他 JS 框架调用 API 时可能会遇到类似下面的错误:
这是因为 asp.net core 默认会限制访问主机的位置和端口,比如上例中 UI 来自 http://localhost:3000,而 API 来自 https://localhost:44159,因为端口后不一致就不让 API 访问了。
解决方案
在主程序中,一般是 program.cs 里加入以下代码:
...
builder.Services.AddCors();
...
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
完整的程序类似于这样:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors();
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.Run();
结论
本文说明了如何在 asp.net core 6 中避免 CORS 错误,也就是给 service 加上 cors 功能,然后在 builder 中允许任何源,标头和方法。