在 Swagger .NET 中启用 Cors

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

我的 .NET Web API 应用程序有这个 program.cs 文件:

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});

var app = builder.Build();

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

app.UseHttpsRedirection();

app.UseCors();

app.MapGet("/", (HttpContext context) =>
{
    context.Response.Redirect("https://www.google.com");
});

app.Run();

如果我运行应用程序并调用 api,它将重定向。但是,当我从 swagger 调用 api 时,它将返回 CORS 错误。如图所示,我已启用 CORS,但它不起作用。

我尝试将 api 移至控制器中并使用 EnableCors 属性,但没有成功。

c# .net cors
1个回答
0
投票

试试这个:

app.UseCors(builder =>
{
    builder.WithOrigins("url to your site")
        .AllowAnyHeader()
        .AllowAnyMethod();
});

将“url to your site”替换为您想要允许调用 API 的网站的 url。

© www.soinside.com 2019 - 2024. All rights reserved.