我正在尝试在我的ASP上启用跨起源资源共享。NET核心Web API,但我卡住了。
EnableCors属性接受字符串类型的policyName作为参数:
// 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上配置CORS。NET核心Web API?
你有三种方式启用CORS:
在中间件中使用命名策略或默认策略。
使用端点路由。
使用[EnableCors]属性。
启用指定策略的CORS:
public class Startup
{
readonly string CorsPolicy = "_corsPolicy";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: CorsPolicy,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
// services.AddResponseCaching();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors(CorsPolicy);
// app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
当使用UseResponseCaching时,UseCors必须在UseResponseCaching之前调用。
开启默认策略下的CORS:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
启用带有端点的CORS
public class Startup
{
readonly string CorsPolicy = "_corsPolicy ";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: CorsPolicy,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers()
.RequireCors(CorsPolicy)
});
}
}
启用带有属性的CORS
你有两个选择
[EnableCors]默认策略。
[EnableCors("{Policy String}")]指定命名策略。