Web Application Cors .NET CORE 3.1 vs 2.1



最近我一直在慢慢切换到.NET CORE 3.1,但是当我尝试移植我的一些Web应用程序(Restful API(时,我遇到了Cors的问题。

运行 .NET CORE 2.1 的项目的代码:

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyOrigin");
app.UseHttpsRedirection();
app.UseMvc();
}

运行 .NET CORE 3.1 的项目的代码:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
// 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();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyOrigin");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

当我向运行 2.1 的 API 发出请求时,一切都按预期进行,但如果我尝试向运行 3.1 的 API 发出相同的请求,我会收到 405 错误(方法不允许错误(。

有没有其他人遇到过这个问题,如果是这样,解决方案是什么?

在配置方法中,移动:

app.UseCors("AllowAnyOrigin");

在两者之间

app.UseRouting();

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

文档中有一个警告,指出必须在这两种方法之间配置 cors 中间件,否则中间件将停止运行。

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

请参阅标有"将 CORS 策略应用于所有终结点"的部分

在管道中配置组件非常棒,因为它可以让您控制,但由于排序限制而非常痛苦,我个人正在等待有人创建一个 VS 附加组件来分析这些组件并发出警告。如果有人有这样的倾向,那将是一个伟大的项目。

最新更新