netcore 跨源资源共享CORS
CORS(Cross-Origin Resource Sharing)是由 W3C 指定的标准,其目的是帮助在各个站点间的资源共享,可以允许配置中的请求源执行允许/拒绝的动作。
要引用程序集 Microsoft.AspNetCore.Cors。
默认开启CORS
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
......
app.UseCors(builder => builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
UseCors要放置在UseAuthorization之前。
路由+命名策略
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "myPolicy",
builder =>
{
builder.WithOrigins("AllowSpecificOrigins", "AllowSpecificOrigins2");
});
});
services.AddControllers();
......
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
......
app.UseCors();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/echo", context => context.Response.WriteAsync("echo")).RequireCors("myPolicy");
endpoints.MapControllers().RequireCors("myPolicy");
});
}
属性启用CORS
最精确地控制跨域请求,可以使用[EnableCors("myPolicy")]与命名策略一同使用,不能定义默认策略和Endpoint路由。
Response跨域
Response.Headers.Add("Access-Control-Allow-Origin", "*");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");