第一步:在appsettings.json文件中配置跨域访问域名,如:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "CorsPaths": { "OriginOne": "http://xxxx.com" //跨域请求网址,跨域添加多个 } }
第二步:Nuget添加Microsoft.AspNetCore.Cors引用
第三步:Startup类添加全局变量:
public readonly string anyAllowSpecificOrigins = "any";//解决跨域
第四步:Startup类中的ConfigureServices方法里添加配置跨域处理cors,代码如下:
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Web", Version = "v1" }); }); services.AddControllers(options => { options.Filters.Add(typeof(ApiExceptionFilter)); }); //解决跨域 services.AddCors(options => { options.AddPolicy(anyAllowSpecificOrigins, corsbuilder => { var corsPath = Configuration.GetSection("CorsPaths").GetChildren().Select(p => p.Value).ToArray(); corsbuilder.WithOrigins(corsPath) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); }
第五步:Startup类中的Configure方法中添加app.UseCors(anyAllowSpecificOrigins),如下代码:
app.UseRouting(); app.UseCors(anyAllowSpecificOrigins);//支持跨域:允许特定来源的主机访问 app.UseAuthorization();
注意:以上三行代码顺序不能换,否则报错!
第六步:Startup类中的Configure方法中添加 .RequireCors(anyAllowSpecificOrigins),如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors(anyAllowSpecificOrigins);//支持跨域:允许特定来源的主机访问 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireCors(anyAllowSpecificOrigins);//支持跨域 }); }
END