Fork me on GitHub

asp.net core webapi 服务端配置跨域

在前后端分离开发中服务端仅仅只为前端提供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()即可允许任意的来源的地址跨域访问(不建议生产环境使用)

posted @ 2017-09-17 18:33  huanent  阅读(4387)  评论(12编辑  收藏  举报