如何使用默认和自己的策略在 ASP.net Core WebAPI 中启用 CORS

ElC*_*ado 1 c# asp.net-core

我想通过 EnableCors 属性为一个控制器启用我自己的“MyPolicy”,而对于其他控制器,我想使用默认策略。所以在我的配置服务方法中我写

services.AddCors(options =>
{
    options.AddPolicy(name: "MyPolicy",
        builder => builder
            .WithOrigins("http://localhost:3000")
            .AllowCredentials()
            .AllowAnyMethod()
            .AllowAnyHeader());

    options.AddDefaultPolicy(
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
});
Run Code Online (Sandbox Code Playgroud)

与我刚刚调用的配置方法相比:

app.UseCors();
Run Code Online (Sandbox Code Playgroud)

它没有按我的预期工作。它仅定义 DefaultPolicy,使用“MyPolicy”的唯一方法是将它们用作:

app.UseCors("MyPolicy");
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,默认策略不起作用。是否可以通过 AddPolicy 定义自己的策略并通过 AddDefaultPolicy 定义默认策略。

ElC*_*ado 5

如果您想使用许多自己的策略和默认策略,解决方案是在configureservices中定义:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(
            builder =>
            {
               
                builder.WithOrigins("http://example.com",
                                    "http://www.contoso.com");
            });

        options.AddPolicy("AnotherPolicy",
            builder =>
            {
                builder.WithOrigins("http://www.contoso.com")
                                    .AllowAnyHeader()
                                    .AllowAnyMethod();
            });

    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud)

并通过 EnableCorsAttribute 使用策略,如下所示:

  // GET api/values
    [EnableCors("AnotherPolicy")]
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "green widget", "red widget" };
    }
Run Code Online (Sandbox Code Playgroud)

。在这种情况下,请勿在配置方法启动类中调用应用程序 IApplicationBuilder 对象的 UseCors 方法。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    //Do not use this method:
    //app.UseCors();

    app.UseHttpsRedirection();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)