WCF Data Service with OData v3 使用jsonp 跨域访问

WCF Data Service with OData  是一个优秀的Restful Web Service在ASP.NET下的实现,但是在使用中,我遇到了一个问题,即当我单独部署WDS服务的时候,Ajax访问就需要跨域。

在一般的WCF服务中,我们可以用JSONP解决。所以我发起了下面这个请求:

你可以看到响应的ContentType是application/json,所以浏览器抛出了一个异常

Refused to execute script from 'http://***.svc/Companies?$filter=Type%20eq%201&$for…on&jsoncallback=jQuery1102003060379653130041_1465881447794&_=1465881447795' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

加粗的部分告诉我们,application/json类型不可执行。JSONP要求回传类型为application/json-p或者text/json-p

但是WDS服务的响应类型只支持Atom、XML和JSON,并不支持JSONP。

最终,在MSDN上看到了一篇Blog,其中有一段:

There are two things needed to support JSONP properly:

  • The ability to control the response format. Data Services uses standard HTTP content type negotiation to select what representation of a given resource should be sent to the client (e.g. JSON, Atom). That requires that the caller can set the Accept request header, which is not possible when doing the JSONP trick (which basically just uses <script> tags). We need to add the ability to use the query string in the URL to select format. (e.g. /People(1)/Friends?$orderby=Name&$format=json).
  • A new option to wrap the response in a callback if such callback was provided in the request (also in the query string). For example /People(1)/Friends?$orderby=Name&$format=json&$callback=loaded.

也就是说只要$format=json并且用$callback定义回调函数就可以了

成功获取数据。~~

转载于:https://www.cnblogs.com/TO-WW/p/5583769.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值