1、Startup配置
1 #region 跨域设置 2 //注意:放到services.AddMvc()之前 3 services.AddCors(options => { 4 options.AddPolicy("any",builder => { 5 6 #region 允许任何来源主机访问 7 builder.AllowAnyOrigin(); 8 #endregion 9 10 #region 允许访问的特定域 11 //builder.WithOrigins("http://*.*.*.*") 12 //.AllowAnyMethod() 13 //.AllowAnyHeader() 14 //.AllowCredentials(); 15 #endregion 16 }); 17 }); 18 #endregion
1 //跨域设置 2 app.UseMiddleware<CorsMiddleware>();
2、自定义Cors中间件
1 /// <summary> 2 /// CORS 中间件 【解决跨域问题】 3 /// </summary> 4 public class CorsMiddleware 5 { 6 private readonly RequestDelegate _next; 7 public CorsMiddleware(RequestDelegate next) 8 { 9 _next = next; 10 } 11 12 public async Task Invoke(HttpContext context) 13 { 14 if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin")) 15 { 16 context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 17 } 18 await _next(context); 19 } 20 }
注意:startup中的Configure中,app.UseMiddleware<CorsMiddleware>()的CorsMiddleware引用为该自定义中间件。