.Net Core 2.0 Web API解决跨域问题:Access to fetch at "***(URL)" from origin "***" has been blocked by CORS policy

这些天做了个需求,需要做个网页展示生产相关数据,数据源已经确定了,于是迅速写好了webapi接口。

前端的话,我用Vue.js在调用webapi时,报了个错误:

Access to fetch at "***(URL)" from origin "***" has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource...

搜索了一下大概了解是跨域问题,怎么解决呢?

也很简单,

在Startup.cs的ConfigureServices函数加上

services.AddCors(x => x.AddPolicy("AllowCors", d => d.AllowAnyOrigin().AllowAnyMethod()));

在Controller加上EnableCors属性

[EnableCors("AllowCors")]

这样用Vue.js调用时就正常了

posted @ 2022-11-14 09:05  新*  阅读(1364)  评论(0编辑  收藏  举报