jQuery Ajax JSONP对WCF服务的后调用主要是400 Bad Request

时间:2012-05-08 16:26:03

标签: json wcf jquery jsonp

嗯,这里有很多关于这个,但我似乎无法将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;
    }

返回“success ID = hello”。

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

如果我使用数据:JSON.stringify({“ID”:“hello”})它会因400错误请求而失败

如果尝试失败,我会尝试使用任何其他数据类型(如int作为Web服务ID(而不是字符串)。

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

有什么想法??? THX

1 个答案:

答案 0 :(得分:4)

默认情况下,WCF操作所期望的正文样式是“裸”,这意味着输入必须由其自身发送(即,它需要"hello"之类的内容。在您的情况下,您是包装在具有参数名称({"ID":"hello"})的对象中。

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