【问题标题】:WCF method not erroring but not receiving my JSONWCF 方法没有出错但没有收到我的 JSON
【发布时间】:2017-03-23 04:54:20
【问题描述】:

我已经为我的 WCF Web 服务设置了以下接口和类,但是当我向它发布 JSON 时遇到问题,发布 XML 工作正常。

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

如果我发布此 XML:

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

我收到了这个回复(如预期的那样):

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

但如果我发布这个 JSON:

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

我收到以下回复:

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

当我在方法上设置断点时,我看到 x 和 y 参数都是 0。

我尝试过发布我的 JSON 的几个不同版本,但都以零的形式出现。奇怪的是,如果我从我发送的 JSON 中删除 'x' 和 'y' 属性(例如{"Test":{}}),它实际上并没有错误,但显然参数仍然为零,但不确定这是否相关:)

【问题讨论】:

  • 您正在使用WebMessageBodyStyle.Wrapped,但您的服务合同似乎不接受任何服务。

标签: c# asp.net json wcf .net-4.6.1


【解决方案1】:

对于这个请求样本 -

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

服务联系人应类似于 -

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

在哪里 -

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

}

【讨论】:

  • 我将其标记为答案只是因为它帮助我理解了我的问题。我发布了错误的数据,我需要发布 JSON {"x":10,"y":10}
【解决方案2】:

感谢 Amit Kumar Ghosh 我找到了答案,如果其他人有这个问题,我的 JSON 不起作用的原因是因为我在发帖:

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

但事实上我应该发布这个:

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

感谢 this 问题的 Amit Kumar Ghosh 和 Konrad Kokosa。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多