0

I have the following OperationContract on my WCF Service:

public int ProcessEntries(Entry[] entries)
{
    return entries.Length;
}

My interface defintion for my OperationContract is as follows:

[OperationContract]
[WebInvoke(
    Method = "POST",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
int ProcessEntries(Entry[] entries);

The Entry class is defined as follows:

[DataContract]
public class Entry
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }
}

I'm calling the OperationContract of the WCF Service via jQuery with the following call:

$.ajax({
    url: 'MyService.svc/json/ProcessEntries',
    type: 'POST',
    data: JSON.stringify({
        entries: [
            { Id: 1, Name: 'Test1' },
            { Id: 2, Name: 'Test2' }
        ]
    },
    contentType: 'application/json',
    success: function (d) { console.log(d); }
});

In Chrome Developer Tools, I see my Request Payload as follows:

{
    "entries": [
        {
            "Id": 1,
            "Name": "Test1"
        },
        {
            "Id": 2,
            "Name": "Test2"
        }
    ]
}

I'm expecting the response to be 2, but I always receive the response of 0.

What am I doing wrong here? Why does my OperationContract think that the array of Entry has a length of 0?


Edit In Debug mode, I can see that the entries array is actually empty. Why would it not be getting the entries from deserializing the JSON sent in the request?


Final Edit I discovered that adding BodyStyle = WebMessageBodyStyle.WrappedRequest to my WebInvoke attribute fixes the problem, but I'm not sure why. Can anyone answer this question?

crush
  • 16,713
  • 9
  • 59
  • 100
  • Did you try marking your `OperationContract` with `[WebInvoke(RequestFormat = WebMessageFormat.Json)]` [MSDN](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webinvokeattribute.requestformat%28v=vs.110%29.aspx) – vutran Jan 15 '14 at 18:00
  • @vutran Yes, I did have that on my OperationContract, but you're on the right track. I just discovered the issue was that I didn't have `BodyStyle = WebMessageBodyStyle.Wrapped`. I guess it would've helped if I had included my interface definition for the OperationContract. Shame on me. – crush Jan 15 '14 at 18:01
  • I'm not really sure why the `BodyStyle = WebMessageBodyStyle.Wrapped` is required. Can anyone give an answer that explains? – crush Jan 15 '14 at 18:04
  • 1
    Please read my answer to [this question](http://stackoverflow.com/questions/20206069/restful-web-service-body-format/20225936#20225936) to see why such format is required in your case. – Konrad Kokosa Jan 15 '14 at 18:06
  • @KonradKokosa Thanks for the link. It's starting to make sense. Perhaps close this as duplicate? – crush Jan 15 '14 at 18:10

0 Answers0