如何使用deafult和自己的策略在ASP.net核心WebAPI中启用CORS



我想通过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());
});

而在配置方法中,我只调用:

app.UseCors();

它没有像我预期的那样工作。它只是定义DefaultPolicy;MyPolicy";将其用作:

app.UseCors("MyPolicy");

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

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

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);
}

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

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

在这种情况下,不要在配置方法启动类中调用应用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();
}

最新更新