1.CORS中间件处理跨源请求。以下代码为具有指定源的整个应用程序启用CORS:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //跨域配置 string[] strs = { "https://localhost:44384" }; app.UseCors(builder => builder.WithOrigins(strs)); app.UseHttpsRedirection(); app.UseMvc(); }
2.跨域策略的定义
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //跨域设置 services.AddCors(Options => { //①允许某一域名的请求 Options.AddPolicy("allow1", builder => { builder.WithOrigins("https://localhost:44384"); }); //②允许所有域名的请求 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, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseCors("allow5"); app.UseHttpsRedirection(); app.UseMvc(); }
在mvc层中开启策略,在Controller、Action头部添加相应策略名称
[EnableCors("allow6")] [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { }