cors-error 尽管端点存在于策略中

cors-error although endpoint exists in policy

我有一个非常简单的 ASP.NET core-webapi,我正试图从我的客户端访问它。客户端是 http://localhost:3000 上的 运行,而我的服务器是 https//localhost:7156 上的 运行。所以我添加了一个策略来接受来自 localhost:3000:

的请求

我的Program.cs:

var builder = WebApplication.CreateBuilder(args);

// basic otel instrumentalisation
builder.Services.AddOpenTelemetryTracing(svc =>
{
    svc.AddSource(new[] { nameof(ServiceController), nameof(StressTestController), nameof(BoundaryPointsController), nameof(AaaServiceClient) }).
        SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName: svcName, serviceVersion: svcVersion)).
        AddHttpClientInstrumentation().
        AddAspNetCoreInstrumentation();
}).AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            builder.WithOrigins("https://localhost:3000",
                "http://localhost:3000", 
                "localhost:3000");
        });
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseHttpsRedirection();    
app.UseCors();     
app.UseAuthorization();    
app.MapControllers();    
app.Run();

我的控制器:

[EnableCors]
[ApiController]
[Route("api/projectdb/[action]")]
public class LoadDataController : ControllerBase
{
    [HttpPost, ActionName("load")]
    public async Task<ActionResult> LoadData() { ... }
}

当我执行来自客户端的请求时,出现 CORS 错误:

const response = await fetch(`https://localhost:7156/api/projectdb/load`, {
        method: 'POST',
        body: '{ }',
        headers: {'Content-Type': 'application/json; charset=UTF-8'} 
    });

这是我得到的错误:

Access to fetch at 'https://localhost:7156/api/projectdb/load' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

错误消息正确:because of the value of your request's Content-Type header,您需要在 CORS 配置中明确允许 header:

// -snip-
.AddCors(options =>
  options.AddDefaultPolicy(builder =>
    builder.WithOrigins("http://localhost:3000")
      .WithHeaders("Content-Type");
  )
);