【问题标题】:WCF Restful Service (Windows Auth) with JSONP带有 JSONP 的 WCF Restful 服务(Windows 身份验证)
【发布时间】:2015-04-21 05:03:30
【问题描述】:

我有一个使用 Windows 身份验证设置的 WCF RESTful 服务,它工作正常。现在我想启用它以进行跨域访问,所以我将我的 js 更改为以下内容:

$.ajax({
         type: "GET",
         url: "http://www.example.com/MyService.svc/GetData",
            contentType: "application/javascript",
            dataType: "jsonp",
            async: false,
            success: function (data) {
                alert($.parseJSON(data));
            },
            error: function (ex) {
                throw ex;
            }
        });

在 Chrome 开发者工具中,在网络选项卡下,我可以看到请求有 200 状态代码,在响应选项卡中,我看到正在返回的数据。但是,在我的 javascript 中,成功块永远不会被调用。它进入错误块并出现错误:

Uncaught #<Object>
$.ajax.error
x.Callbacks.c
x.Callbacks.p.fireWith
k
x.ajaxTransport.send.n.onload.n.onreadystatechange

我错过了什么?

【问题讨论】:

  • 我认为 contentType 应该是“application/json; charset=utf-8”。

标签: javascript wcf rest jsonp


【解决方案1】:

如果将 contenttype 更改为 "application/json; charset=utf-8" 不能解决问题,那么您可以尝试以下代码:

如果您想启用它以进行跨域访问,那么您应该在 global.asax.cs 文件中包含以下代码。

    protected void Application_BeginRequest(object sender, EventArgs e)
    {   
        EnableCrossDmainAjaxCall();
    }
    private void EnableCrossDmainAjaxCall()
    {
        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", "POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

您可以编写如下代码的ajax调用函数:

$.ajax({
        isPostBack: false,
        type: "GET",
        url: "http://www.example.com/MyService.svc/GetData",
        async: false,
        cache: false,
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        data: '{}',
        dataType: 'json',
        crossDomain: true,
        success: function (data) {
            alert($.parseJSON(data));
        },
        error: function (ex) {
            throw ex;
        }
    });

【讨论】:

    猜你喜欢
    • 2011-12-15
    • 2011-03-03
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2012-08-31
    • 2011-06-08
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多