如何摆脱 .net core 2.2 中的 CORS?

How to get rid of CORS in .net core 2.2?

我已经将我的项目更新到 .net core 2.2,似乎 CORS 出现了 2.1 中没有的问题。

我是 运行 我的应用 URL:http://*:5300

我在 Startup.cs:

中添加了这段代码
public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddCors(options =>
                     options.AddPolicy("MyPolicy", builder =>
                     {
                         builder.AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowCredentials()
                                .AllowAnyHeader();
                     }));

    services.AddMvc();

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    app.UseCors(builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowCredentials()
               .AllowAnyHeader();
    });

    app.UseAuthentication();
    app.UseMvc();
}

这没有用,所以我在我的 `BaseController" class:

上添加了 [EnableCors] 属性
[EnableCors]
[Authorize]
[Produces("application/json")]
[Route("api/[controller]")]
public class BaseController : Controller
{

}

但我仍然收到此 CORS 错误:

Access to XMLHttpRequest at 'http://192.168.15.63:5301/api/permissions/UI' from origin 'http://192.168.15.63:5302' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我还能做什么才能完全删除 CORS?

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

在使用 ASP.NET 核心响应 CORS 请求时,您不能同时使用 AllowAnyOriginAllowCredentials

Access to XMLHttpRequest at 'http://192.168.15.63:5301/api/permissions/UI' from origin 'http://192.168.15.63:5302' has been blocked by CORS policy

此消息显示您的 服务器 正在侦听 http://192.168.15.63:5301,但您的 客户端 正在从 http://192.168.15.63:5302。由于端口不同,这些是不同的来源,因此使用CORS保护。

要使请求成功,请将您的 ASP.NET CORS 配置代码更新为如下所示:

builder.WithOrigins("http://192.168.15.63:5302")
    .AllowAnyMethod()
    .AllowCredentials()
    .AllowAnyHeader();

这将 客户端 的来源配置为受 CORS 支持 - 当然,您可以将其作为配置选项添加到应用程序本身(使用例如 appsettings.json), 如果需要的话。


旁白:

由于您已调用 AddCors 并配置了命名策略,因此没有理由在对 UseCors 的调用中配置相同的策略 - 您只需传入策略名称即可您之前使用 AddCors:

配置
app.UseCors("MyPolicy");