A small gotcha when calling a WCF service using $.ajax
I just spent a couple of hours debugging a Jquery call to a WCF Service and luckily stumbled on a solution. I though I’d share it with the universe.
Here is the basic setup that was causing issues.
The WCF Service
public class JsonResponse {
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
[ServiceContract(Namespace="FooBar.Services")]
public interface IServices
{
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/FooBar",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
JsonResponse FooBar(string foo, string bar);
}
Calling the Service with the following Ajax call
var data = {
"foo" : "bar",
"bar" : "foo"
};
$.ajax({
type : "POST",
url : "/Services/Services.svc/FooBar",
contentType: "application/json",
data : data,
success : function(data){
if(data.success){
alert('BAM');
}
},
dataType : "json"
});
Returns this error The server encountered an error processing the request. The exception message is ‘OperationFormatter encountered an invalid Message body. Expected to find an attribute with name ‘type’ and value ‘object’. Found value ‘boolean’.’. See server logs for more details. The exception stack trace is:
The solution.
Luckily it’s pointing to the Json Serializer not being able to deserialize the request. After looking closely at multiple examples on the web something jumped at me. Examples seem to pass and textual representation of the object and not the Json object itself. What the ajax call does for you here is depending on the “type” option, “POST”, “GET” etc…, it will convert the data (json format) option to a foo=bar&bar=foo format and add it to the appropriate output. If you use POST it will put it the the body of the request. If you use GET it will put it in the querystring.
In order to fix this I need to pass the data as a stringified version of the json object. At that point the ajax call will not convert when adding to the body of the request.
This is the new javascript that works
var data = {
"foo" : "bar",
"bar" : "foo"
};
$.ajax({
type : "POST",
url : "/Services/Services.svc/FooBar",
contentType: "application/json",
data : JSON.stringify(data),
success : function(data){
if(data.success){
alert('BAM');
}
},
dataType : "json"
});
I used the JSON library found here
Hopefully this will save someone out there some time when debugging this issue. I’m quite certain it’s happened to someone out there.
S.


