【问题标题】:jQuery Ajax JSONP Post call to WCF Service mostly gets 400 Bad Request对 WCF 服务的 jQuery Ajax JSONP Post 调用大多得到 400 Bad Request
【发布时间】:2012-05-17 04:01:56
【问题描述】:

嗯,这里有很多关于此的内容,但我似乎无法将 JSON 对象传递给 Web 服务对象。我能做的最接近的就是这个例子,其中 ID 与服务中的字符串变量名匹配,如下所示

        var jsonData = { "ID": "hello" };
        $.ajax({
            url: "http://blah/blah.svc/GetPersonByID",
            type: "POST",
            dataType: "jsonp",  // from the server
            contentType: "application/json; charset=utf-8", // to the server
            data: jsonData,
            success: function (msg) {
                alert("success " + msg.Name);
            },
            error: function (xhr, status, error) {
                alert(xhr.status + " " + status + " " + error);
            }
        });

WCF 服务在哪里

    [OperationContract]
    [Description("Returns a person by ID.")]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    Person GetPersonByID(string ID);

    public Person GetPersonByID(string ID) {
        Person person = new Person {
            Name = ID,   // "Bob",
            FavoriteColor = "Red",
            UserID = 1 //int.Parse(ID)
        };
        return person;
    }

这将返回“成功 ID=hello”。

为什么它返回 ID=hello,而不仅仅是 hello?

如果我使用 data: JSON.stringify({ "ID": "hello" }) 它会失败并返回 400 bad request

如果我尝试任何其他数据类型,例如网络服务 ID 的 int(而不是字符串)如果失败。

如果我尝试任何更复杂的数据类型,它会失败。

有什么想法吗???谢谢

【问题讨论】:

    标签: json wcf jquery jsonp


    【解决方案1】:

    默认情况下,WCF 操作期望的主体样式是“bare”,这意味着输入必须自己发送(即,它期望像"hello" 这样的东西。在你的情况下,你是包装 它在一个带有参数名称 ({"ID":"hello"}) 的对象中。

    您可以使操作期望包装输入(通过将WebInvoke 属性的BodyStyle 属性设置为WebMessageBodyStyle.WrappedRequest(和JSON.stringify 您的数据),或者将传递给$.ajax 的参数更改为只需发送 JSON 字符串 (data: "\"hello\"")。

    【讨论】:

    • 天啊!我已经为此工作了3天!你摇滚。这解决了从 asp.net 访问服务时的问题。我还没有在 jQuery 中对此进行测试,但我对此感觉很好。
    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多