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

时间:2018-12-26 12:53:10

标签: c# asp.net-core asp.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'类上添加了[EnableCors]属性:

[EnableCors]
[Authorize]
[Produces("application/json")]
[Route("api/[controller]")]
public class BaseController : Controller
{

}

但是我仍然收到此CORS错误:

  

CORS政策已阻止从来源“ http://192.168.15.63:5301/api/permissions/UI”访问“ http://192.168.15.63:5302”处的XMLHttpRequest:
  对预检请求的响应未通过访问控制检查:
  当请求的凭据模式为“ include”时,响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ *”。
  XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

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

1 个答案:

答案 0 :(得分:5)

  

当请求的凭据模式为“ include”时,响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ *”。

如该消息所示,在使用ASP.NET Core响应CORS请求时,不能同时使用AllowAnyOriginAllowCredentials

  

CORS策略已阻止从来源“ http://192.168.15.63:5301/api/permissions/UI”访问“ http://192.168.15.63:5302”处的XMLHttpRequest

此消息表明您的服务器正在监听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支持的 client 的来源-当然,您可以将其作为配置选项添加到应用程序本身(例如,使用appsettings.json)需要。


尽管可以解决您的特定问题,但根据上面的代码,我还是要提供一些辅助说明。

您已经致电AddCors并配置了命名策略,因此没有必要在对UseCors的调用中配置相同的策略-您只需输入配置的策略名称即可早于AddCors

app.UseCors("MyPolicy");