1、在Startup类里先定义一个全局变量。
1 private readonly string AllowCors= "AllowCors";
2、在Startup的ConfigureServices中添加以下代码来配置跨域处理。
1 #region 跨域 2 services.AddCors(options => 3 { 4 options.AddPolicy(AllowCors, 5 builder => 6 { 7 builder.AllowAnyMethod() 8 .AllowAnyOrigin() 9 .AllowAnyHeader(); 10 }); 11 }); 12 #endregion
3、在Startup的Configure中添加以下代码来配置跨域处理。
1 app.UseRouting(); 2 //CORS 中间件必须配置为在对 UseRouting 和 UseEndpoints的调用之间执行。 3 app.UseCors(AllowCors); 4 app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
如果cors报错了,就通过NuGet安装 Microsoft.AspNetCore.Cors
PS:如果需要配置指定域名跨域,需要使用 WithOrigins ,请参考:https://blog.csdn.net/DavidLeeFeng850122/article/details/105102984/
感谢:
https://www.cnblogs.com/jardeng/p/12611535.html