public void ConfigureServices(IServiceCollection services)
{
services.AddCors(Options =>
{
//无任何限制
Options.AddPolicy("any", builder =>
{
builder.AllowAnyHeader().AllowAnyMethod().AllowAnyHeader();
});
//②允许所有域名的请求
Options.AddPolicy("allow2", builder =>
{
builder.AllowAnyOrigin();
});
//③允许某域名的请求,且限制该请求的类型
Options.AddPolicy("allow3", builder =>
{
builder.WithOrigins("https://localhost:44384").WithMethods("POST", "HEAD");
//builder.WithOrigins("https://localhost:44384").AllowAnyMethod();//允许任何http请求的方法
});
//④允许某域名的请求,带请求头部信息
Options.AddPolicy("allow4", builder =>
{
builder.WithOrigins("https://localhost:44384").WithHeaders("accept", "content-type", "origin", "x-custom-header");
//builder.WithOrigins("https://localhost:44384").AllowAnyHeader();//
//builder.WithOrigins("https://localhost:44384").WithExposedHeaders("x-custom-header");//指定的说明文头信息
});
//⑤允许某域名的请求,预检时间多久可以被缓存
Options.AddPolicy("allow5", builder =>
{
builder.WithOrigins("https://localhost:44384").SetPreflightMaxAge(TimeSpan.FromSeconds(2520));
});
Options.AddPolicy("allow6", builder =>
{
builder.WithOrigins("https://localhost:44384");
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
//....
app.UseRouting();
//添加需要的设置
app.UseCors("any");
//...
app.UseAuthorization();
//...
}
//使用
[Microsoft.AspNetCore.Cors.EnableCors("any")]
public class APPController :Controller{}