0

I have setup the following interface and class for my WCF web service, but am having a problem when I post JSON to it, posting XML works fine.

[ServiceContract]
public interface IWebService {
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "xml/post")]
    [return: MessageParameter(Name = "data")]
    int Test(int x, int y);
}

public class WebService : IWebService {
    public int Test(int x, int y) {
        return x + y;
    }
}

If I post this XML:

<Test xmlns="http://tempuri.org/"><x>10</x><y>10</y></Test>

I get this this response (as expected):

<TestResponse xmlns="http://tempuri.org/"><data>20</data></TestResponse> 

But if I post this JSON:

{"Test":{"x":10,"y":10}} 

I get this response:

<TestResponse xmlns="http://tempuri.org/"><data>0</data></TestResponse> 

And when I put a breakpoint on the method I see that the x and y parameters are both 0.

weirdness

I've tried posting several different versions of my JSON, but all come through as zeros. Oddly, if I remove the 'x' and 'y' properties from the JSON I send (e.g. {"Test":{}}), it doesn't actually error, but obviously the parameters are still zero, not sure if this related though :)

MadSkunk
  • 3,309
  • 2
  • 32
  • 49

2 Answers2

1

For this sample of request -

{"Test":{"x":10,"y":10}} 

The Service contact should look something like -

public int Test(Model Test) {
    return test.x + test.y;
}

where -

public class Model{
    public int x { get; set; }
    public int y { get; set; }

}
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24
  • I'll mark this as the answer simply because it helped me understand my issue. I am posting the wrong data, I need to post the JSON `{"x":10,"y":10}` – MadSkunk Nov 09 '16 at 11:46
0

Thanks to Amit Kumar Ghosh I worked out the answer, if anyone else has this problem, the reason my JSON wasn't working was because I was posting:

{"Test":{"x":10,"y":10}} 

But in fact I should have been posting this:

{"x":10,"y":10}

A combination of thanks go to Amit Kumar Ghosh and Konrad Kokosa from this question.

Community
  • 1
  • 1
MadSkunk
  • 3,309
  • 2
  • 32
  • 49