简体   繁体   English

jQuery Ajax JSONP对WCF服务的调用大部分会收到400错误请求

[英]jQuery Ajax JSONP Post call to WCF Service mostly gets 400 Bad Request

Hmm well there's lots here about this but I can't seem to get a JSON object through to a web service object. 嗯,这里有很多相关内容,但是我似乎无法将JSON对象传递到Web服务对象。 The closest I can get to making this work is this example, where ID matches the string variable name in the service as follows 我最接近完成这项工作的是此示例,其中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);
            }
        });

Where the WCF service is this 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;
    }

This returns "success ID=hello". 这将返回“成功ID = hello”。

Why does it return ID=hello, instead of just hello? 为什么它返回ID = hello,而不仅仅是问候?

If I use data: JSON.stringify({ "ID": "hello" }) it fails with 400 bad request 如果我使用数据:JSON.stringify({“ ID”:“ hello”})失败,并显示400错误请求

If I attempt any other data type like an int for the web service ID (instead of string) if fails. 如果我尝试任何其他数据类型(例如,int)作为Web服务ID(而不是字符串),则失败。

If I attempt any more complex data types it fails. 如果我尝试任何更复杂的数据类型,它将失败。

Any thoughts??? 有什么想法吗??? Thx 谢谢

By default the body style expected by a WCF operation is "bare", which means that the input must be sent by itself (ie, it expects something like "hello" . In your case you're wrapping it in an object with the parameter name ( {"ID":"hello"} ). 默认情况下,WCF操作期望的主体样式为“裸露”,这意味着输入必须由自身发送(即,它期望像"hello"类的东西。在这种情况下,您要将其包装在带有参数的对象中)名称( {"ID":"hello"} )。

You can either make the operation expect the wrapped input (by setting the BodyStyle property of the WebInvoke attribute to WebMessageBodyStyle.WrappedRequest (and JSON.stringify your data), or change the parameter passed to $.ajax to simply send the JSON string ( data: "\\"hello\\"" ). 您可以使操作期望包装的输入(通过将BodyStyle属性的WebInvoke属性设置为WebMessageBodyStyle.WrappedRequest (和JSON.stringify您的数据),或更改传递给$ .ajax的参数以仅发送JSON字符串( data: "\\"hello\\"" )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM