你的位置:首页 > ASP.net教程

[ASP.net教程]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、

最终,在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定义回调函数就可以了

成功获取数据。~~