In my service contract I have:
[OperationContract(Name = "TreeViewData")]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
TreeData[] TreeViewData(string RagId);
The Tree data class is simple
public interface ITreeDataV1
{
string Id { get; set; }
string ParentId { get; set; }
string Text { get; set; }
string Value { get; set; }
}
[DataContract(Name = "TreeData",
Namespace = "http://xxx.com/2011/10/14/TreeDataV1")]
public class TreeData : ITreeDataV1
{
[DataMember(Name = "Id")]
public string Id { get; set; }
[DataMember(Name = "ParentId")]
public string ParentId { get; set; }
[DataMember(Name = "Text")]
public string Text { get; set; }
[DataMember(Name = "Value")]
public string Value { get; set; }
}
And in my service logic itself I have:
public TreeData[] TreeViewData(string RagId)
{
// some code and return some array of TreeData
}
My problem is when I create my jquery $.ajax request as:
$.ajax(
{
type: "POST",
url: "http://xxx/Retriever.svc/UI/TreeViewData",
data: {"RagId":"121"},
dataType: "json",
success: function()
{
alert('pop the champagne');
}
}
);
I get the following exception –
The incoming message has an unexpected message format ‘Raw’. The
expected message formats for the operation are ‘Xml’, ‘Json’. This can
be because a WebContentTypeMapper has not been configured on the
binding.
I’m almost certain the error is in how I formatted the data bit of the request.
Any pointers?
The entire data object needs to be stringified. An easy way to accomplish this is to use the JSON.Stringify method in the JSON2 library. (https://github.com/douglascrockford/JSON-js/blob/master/json2.js)
Using it would change it to:
Doing it manually would look something like:
However this approach is inflexible and becomes a time waster when trying to manually stringify complex/dynamic objects.