如何修复 ASP.NET Core 8 应用程序中的 cors 错误?

问题描述 投票:0回答:1

几天来,我一直在尝试解决遇到的 CORS 问题,但是我已经在

Program.cs
文件中进行了很多尝试来尝试解决此问题,但我无法弄清楚。

基本上 CORS 错误仅发生在

POST
方法上。

我在

Program.cs
中有这个代码:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

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

builder.Services.AddCors(builder =>
{
    builder.AddPolicy("AllowAll", options =>
    {
        options.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseCors("AllowAll");

app.UseAuthorization();

app.MapControllers();

app.Run();

在浏览器控制台中我看到这个:

从源“https://example.com”访问“https://localhost:7278/api/Topaz/SetTabletState”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于所请求的资源上。

谁能帮我解决这个问题?

我已经尝试将域名放在源上,但仍然不起作用。

我已经尝试在控制器中定义 CORS 策略,但仍然不起作用。

c# asp.net-core asp.net-core-webapi
1个回答
0
投票

不久前,我遇到了同样的错误。为了解决这个问题,我只是在program.cs中添加了一个代码片段。

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .SetIsOriginAllowed(origin => true)
);

app.UseAuthentication();
© www.soinside.com 2019 - 2024. All rights reserved.