将ASP web api应用程序从.netcore2.*迁移到net6.0后出现的CORS问题 &g



我们的代码与netcore2升级期间所做的更改发生冲突。在我们一直升级到net6.0的过程中*到netcore3.0

遵循MS文章中的指导方针意味着我现在在我们的客户端应用程序中看到这个错误:

Access to fetch at <url1> from origin <url2> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

有一种方法来实现通配符CORS与认证?

新代码(net 6.0)

InConfigureServices:

services.AddCors();
services.AddMvc(o => o.EnableEndpointRouting = false)
.AddNewtonsoftJson(options => { ... });

InConfigure:

app.UseCors(configurePolicy =>
{
configurePolicy.AllowAnyOrigin();
configurePolicy.AllowAnyHeader();
configurePolicy.AllowAnyMethod();
//configurePolicy.AllowCredentials();  
});
app.UseMiddleware<OptionsMiddleware>();
app.UseMiddleware<BearerTokenMiddleware>();
app.UseWebSockets();
app.UseMvc();

旧代码(net 2.2) -工作!

InConfigureServices:

services.AddCors();
services.AddMvc()
.AddJsonOptions(options => { ... });

InConfigure:

app.UseCors(configurePolicy =>
{
configurePolicy.AllowAnyOrigin();
configurePolicy.AllowAnyHeader();
configurePolicy.AllowAnyMethod();
configurePolicy.AllowCredentials();
});
app.UseMiddleware<OptionsMiddleware>();
app.UseMiddleware<BearerTokenMiddleware>();
app.UseWebSockets();
app.UseMvc();

注意上面AddMvc的变化,需要在UseCors中注释掉AllowCredentials

项目类型为Microsoft.NET.Sdk.Web

我使用的代码是

app.UseRouting();    
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials

应该是这样的:D

相关内容

  • 没有找到相关文章

最新更新