在前后端分离开发中服务端仅仅只为前端提供api接口,并且前后端往往单独部署,此时就会出现浏览器跨域问题。asp.net core提供了简单优雅的解决方案。

在startup文件的Configure添加如下代码(替换“http://localhost:8080”为你的前端部署地址,此处测试的前端地址为本地的8080端口)

注:asp.net core2.0以下需安装nuget包:Microsoft.AspNetCore.Cors

app.UseCors(builder =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.WithOrigins("http://localhost:8080");
            });

如果在开发环境只需替换builder.WithOrigins("http://localhost:8080")为builder.AllowAnyOrigins()即可允许任意的来源的地址跨域访问(不建议生产环境使用)

相关文章:

  • 2021-07-26
  • 2022-12-23
  • 2021-09-27
  • 2021-10-18
  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2021-10-16
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2021-10-19
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2021-07-27
相关资源
相似解决方案