首页 > 解决方案 > 在 WCF 中从 POST 检索数据时出现问题

问题描述

因此,我使用 WCF 服务在数据库中插入数据,为此我将 POST 中的数据发送到我的 WCF 服务并使用 DataContract 收集它,如下所示:

POST 发送的 JSON 数据

{ "data": { "subsidiarySid":"0", "storesid":"0", "date":"2018-06-15", "counters": [ { "nation":"France", "count":"5" }, { "nation":"France", "count":"5" } ] } }

数据合约

[DataContract(Name ="data")]
    public class Count
    {
    [DataMember(Name ="subsidiarySid")]
    public string subsidiarySid;

    [DataMember(Name ="storeSid")]
    public string storeSid;

    [DataMember(Name = "date")]
    public string date;

    [DataMember(Name = "counters")]
    public IEnumerable<Counter> counters;
}

[DataContract]
public class Counter
{
    [DataMember(Name = "nationalitySid")]
    public string nationalitySid;

    [DataMember(Name = "count")]
    public string count;
}

接口中的方法

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "count_customers")]
string PostCount(Count count);

问题是当我尝试访问这个对象时,我得到一个空值......我的合同是错误的还是我在其他地方搞砸了?我也可以摆脱 json 开头的“data{}”(比如直接在 json 的根目录下使用我的“subsidiarySid 等)吗?

标签: jsonwcfpost

解决方案


毕竟找到了自己的方式,所以我将其发布为将来参考的答案。我所做的是从 DataContract 中获取字符串属性(在 OperationContract 中按名称获取它们,如下所示:

[OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "count_customers")]
    string PostCount(string subsidiarySid, string storeSid, string date, IEnumerable<Counter> counters);

和数据合同

[DataContract(Name = "counter")]
public class Counter
{
    [DataMember(Name = "nationalitySid")]
    public string nationalitySid;

    [DataMember(Name = "count")]
    public string count;
}

只需删除 DataContract 定义中的“名称”属性,我就可以省略不必要的“数据:{}”层。


推荐阅读