WCF method not erroring but not receiving my JSON

拈花ヽ惹草 提交于 2019-12-12 05:19:07

问题


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.

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


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

}



回答2:


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.



来源:https://stackoverflow.com/questions/40505971/wcf-method-not-erroring-but-not-receiving-my-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!