WCF:嵌套的DataContract值为null

时间:2018-01-31 10:29:02

标签: c# xml wcf

我正在编写一个接受XML数据的WCF服务。但是,当我使用该服务时,它接收的参数具有空值。

这是我的服务合同:

[OperationContract]
        [ServiceKnownType(typeof(ECardPaymentModel))]
        [ServiceKnownType(typeof(TransactionInformation))]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "ECardPayment")]
        string ECardPayment(ECardPaymentModel Payment);

数据合同:

[DataContract(Name = "Payment", Namespace = "")]
    [Serializable]
    public class ECardPaymentModel
    {
        [DataMember(Name = "TransactionInfo")]
        public TransactionInformation TransactionInfo { get; set; }
    }

    [DataContract(Name = "TransactionInfo")]
    public class TransactionInformation
    {
        [DataMember(Name = "customer")]
        public string Customer { get; set; }

        [DataMember(Name = "transid")]
        public string TransID { get; set; }
    }

我用来调用服务的XML:

<Payment>
    <TransactionInfo>
           <customer>HD000083</customer>
           <transid>1001</transid>
    </TransactionInfo>
</Payment>

但是,我收到的Payment.TransactionInfo.CustomerPayment.TransactionInfo.TransID的值均为空。

我不知道我哪里错了。因为当我使用平面物体时,比如

    [DataContract(Name = "Payment")]
    public class ECardPaymentModel
    {
        [DataMember(Name = "customer")]
        public string Customer { get; set; }

        [DataMember(Name = "transid")]
        public string TransID { get; set; }
    }

和XML一样,

<Payment>
           <customer>HD000083</customer>
           <transid>1001</transid>
</Payment>

我收到了Payment.CustomerPayment.TransID的正确值。

2 个答案:

答案 0 :(得分:1)

您的TransactionInformation似乎有默认的xml命名空间,但您不能将其传递给customertransid

您应该尝试删除默认命名空间,方法是设置DataContract(..., Namespace = "")TransactionInformation,就像您ECardPaymentModel类一样。

答案 1 :(得分:1)

尝试在DataInformation中为TransactionInformation添加Namespace =“”。如果这不起作用,请告诉我。