zoukankan      html  css  js  c++  java
  • 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定义回调函数就可以了

    成功获取数据。~~

  • 相关阅读:
    浏览器渲染流程
    MVC模式
    传统的DOM是如何进行渲染的
    报文的概念及理解
    单页面开发与多页面开发的优缺点
    第4次作业
    售票系统
    第三次作业
    第二次作业
    第一次作业
  • 原文地址:https://www.cnblogs.com/TO-WW/p/5583769.html
Copyright © 2011-2022 走看看