繁体   English   中英

我真的需要 CORS 和 Swagger 吗?

[英]Do I really need CORS here with Swagger?

我有一个内部开发的 API 用于从 SQL 服务器数据库中提取数据。 我注意到的一件事是它使用的是 CORS,老实说,我不知道它是如何到达这里的。

为什么我需要这样做? 当 API 按原样工作时,有什么好处。

程序.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();

//do I really need this!?!
builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

var startup = new Startup(builder.Configuration);
startup.ConfigureServices(builder.Services);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

startup.Configure(app);

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

app.UseHttpsRedirection();

//why!?!
app.UseCors("corsapp");

app.UseAuthorization();

app.MapControllers();

app.Run();

您需要知道您的程序是否为从其他域加载的客户端应用程序提供 API 响应,以确定您是否需要启用 CROS。

例如,对于 CORS 支持,有两种情况不需要执行任何操作:

  1. Swagger UI 托管在与应用程序本身相同的服务器上(相同的主机和端口)。
  2. 该应用程序位于启用所需 CORS 标头的代理后面。 这可能已经包含在您的组织中。

您可以通过 这个链接这个官方文档来更好地理解和使用 CROS。

希望这可以帮到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM