Hmm well there's lots here about this but I can't seem to get a JSON object through to a web service object. The closest I can get to making this work is this example, where ID matches the string variable name in the service as follows
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
[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".
Why does it return ID=hello, instead of just hello?
If I use data: JSON.stringify({ "ID": "hello" }) it fails with 400 bad request
If I attempt any other data type like an int for the web service ID (instead of string) if fails.
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"}
).
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\\""
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.