gpt4 book ai didi

c# - Asp.net Core 3.0 CORS 根据官方文档无法正常工作

转载 作者:行者123 更新时间:2023-12-05 02:10:28 26 4
gpt4 key购买 nike

我想为 Asp.Net Core 3.0 API 项目启用 CORS。这是生成的基本 Asp.Net Core Api 模板。一切都是模板的默认设置,除了我从文档中添加了 CORS 设置:Enable Cross-Origin Requests (CORS) in ASP.NET Core

这是我的 Startup.cs

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("localhost", "www.google.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseCors("CorsPolicy");
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

这些是我的响应 header : enter image description here

我应该如何设置才能在响应中获取正确的 CORS header ?

这是我的 fetch api 测试: enter image description here

最佳答案

糟糕,我成功解决了这个问题。

这个组合对我来说是唯一的,什么是有效的:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(); //This needs to let it default
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseCors(
options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
); //This needs to set everything allowed

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

关于c# - Asp.net Core 3.0 CORS 根据官方文档无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com