没想到多年之后我还得继续写这些东西.... 瀑布汗~
最近不得不开始研究用web api
MVC的项目中,在js文件里,实现点击一个按钮调用外部发布好的api,再从api把值回传给js页面,跳转。
经测试下面两种方法均有效获得api返回值。
function testinfo(id) { $.ajax({ url: "http://158.14.51.103/api/Verify/Get", type: ‘GET‘, dataType: ‘JSON‘, data: { Id: id, Key: "123456", FUrl: "./SalesSetting" }, success: function (data) { alert("123 " + data.FUrl); console.log(data.FUrl); } }); $.get(‘http://158.14.51.103/api/Verify/Get‘, { Id: id,Key:"123456",FUrl:"./SalesSetting"}, function (result) { console.log(result.Key); }); }
不过,最开始调用api的时候不停的报下面的错误。
XMLHttpRequest cannot load http://158.14.51.103/api/Verify/Get?Id=30054&Key=123456&Token=&FUrl=.%2FSalesSetting. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://localhost:5955‘ is therefore not allowed access. The response had HTTP status code 404.
查了一下网上好多人说是chome浏览器的问题,但是在浏览器属性里加Access-Control-Allow-Origin字符串的方式并不好用,后来查到了下面这个网址,国外也有人在问这个问题。
http://stackoverflow.com/questions/27504256/mvc-web-api-no-access-control-allow-origin-header-is-present-on-the-requested
You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Please note that the Methods are all individually specified, instead of using *
. This is because there is a bug occurring when using *
.
You can also enable CORS by code.
把上面那段代码加入config就解决了~ 感动!
下面的网页也有提到这个问题
http://blog.csdn.net/starfd/article/details/45307659
2、config方式实现CORS
在Web.config的system.webServer配置节下增加配置,这种方式的好处是简单,只要在这里加了这个配置,那么所有的api都可以按同一种规则支持跨域请求
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /> </customHeaders> </httpProtocol>
如果是HTTP Basic Access authentication,似乎还需要个<add name="Access-Control-Allow-Credentials" value="true" />,此处还未验证
最后补充个Cors相关说明:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-02.html
以及官方链接:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
另外,关于web api 在IIS上的部署,我只想大声疾呼——IIS如果是后装的记得要注册记得要注册记得要注册!!!
好了,希望我能在web api的迫害下,顺利的活到下周!!!