如何修复 .NET APP 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();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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
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.