1 增加Middleware
/// <summary> /// 响应跨域 /// </summary> public class CorsMiddleware { private readonly RequestDelegate _next; public CorsMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin")) { context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); } if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Methods")) { context.Response.Headers.Add("Access-Control-Allow-Methods", "*"); } if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Headers")) { context.Response.Headers.Add("Access-Control-Allow-Headers", "authorization,content-type"); } if (context.Request.Method == "OPTIONS") { context.Response.StatusCode = 200; return; } await _next(context); } }
2 Startup中的配置
public void ConfigureServices(IServiceCollection services) { services.AddCors(option => { option.AddPolicy("any", builder => { builder.WithOrigins("http://*.*.*.*").AllowAnyMethod().AllowAnyHeader().AllowCredentials(); }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<CorsMiddleware>(); app.UseAuthorization(); // 使用any app.UseCors("any"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }