小编典典

如何在ASP.NET Core中启用CORS

c#

我试图在我的ASP.NET Core Web API上启用跨源资源共享,但是我遇到了麻烦。

EnableCors属性接受policyName类型string作为参数:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

是什么policyName意思,如何在ASP.NET Core Web API上配置 CORS


阅读 373

收藏
2020-05-19

共1个答案

小编典典

您必须使用以下ConfigureServices方法在应用程序启动时配置CORS策略:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

    // ...
}

使用CorsPolicyBuilderbuilder您可以根据需要配置策略。现在,您可以使用此名称将策略应用于控制器和操作:

[EnableCors("MyPolicy")]

或将其应用于每个请求:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    // ...

    // This should always be called last to ensure that
    // middleware is registered in the correct order.
    app.UseMvc();
}
2020-05-19