MadSkunk MadSkunk - 1 month ago 9
JSON Question

WCF method not erroring but not receiving my JSON

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 :)

Answer

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; }

}