Webapi 跨域 解决解决错误No 'Access-Control-Allow-Origin' header is present on the requested resource 问题

首先是web端(http://localhost:53784) 请求 api(http://localhost:81/api/)时出现错误信息:

查看控制台会发现错误:XMLHttpRequest cannot load http://localhost:81/api/. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://localhost:53784‘ is therefore not allowed access.

这时会发现并没有阻止请求的发送,而是阻止了不同源请求的响应。也就是说请求没有问题,问题出在了响应。那么如何对指定的源开放访问???

第一步:首先在工具里面打开输入;Install-Package Microsoft.AspNet.WebApi.Cors  回车。

第二步:等第一步完成后 打开App_Start/WebApiConfig.cs. 添加一下代码:  config.EnableCors();

第三步:在需要访问的Controlls上面加这样的属性:  [EnableCors(origins: "http://localhost:53784", headers: "*", methods: "*")]

现在可以再试试看看效果。如果可以请给个赞 希望帮助到更多的人。

猜你喜欢

转载自www.cnblogs.com/bin521/p/9211743.html
今日推荐