由于CORS,JayData无法读取WCF数据服务

时间:2014-05-06 13:06:07

标签: jquery cors wcf-data-services jaydata

我创建了一个WCF数据服务,并在我的网页中设置了以下内容:

 var mongo = new MyCtx.MyContext({ name: 'oData', oDataServiceHost: 'http://xxxxxxxxx/MongoDataService.svc/', enableJSONP: false });

在我的WCF数据服务web.config中:

 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Max-Age" value="3600" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, MaxDataServiceVersion" />
        <add name="Access-Control-Allow-Methods" value="PUT, POST, GET, DELETE, MERGE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

当我尝试打开它时,我收到以下错误:

SEC7118:  http://xxxxxxxxxxxxxx/MongoDataService.svc//DataTable1 " XMLHttpRequest for [URL] required Cross Origin Resource Sharing(CORS). 
SEC7119: "XMLHttpRequest for [URL] required CORS preflight."
SCRIPT7002: XMLHttpRequest: Network problem 0x80070005, Access denied.

我的IIS服务器定义了以下标头:

enter image description here

我还应该做些什么?

1 个答案:

答案 0 :(得分:0)

添加您的WCF数据服务文件Global.asax(如果您还没有)。 然后处理BeginRequest事件,并添加代码:

  protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, MERGE" );
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, MaxDataServiceVersion, DataServiceVersion, Authorization");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

然后它应该工作:)