如何获取在 WCF 服务上序列化的可为 null 的 DateTime

How to get a nullable DateTime serialized on WCF service

我有一个 WCF 服务,在 DataContract 中有一个 nullable 日期时间成员,如下所示。由于业务规则,此 datamember 不能将 EmitDefaultValue 设置为 true 并且类型必须是一个“日期时间?” .

[DataContract(Name = "DADOS")]
public class Dados 
{
    [DataMember(EmitDefaultValue = false, Name = "NASCIMENTO")]
    public DateTime? DtNascimento = null;
}

我的服务合同如下所示,看到我必须有两个版本的 Webinvoke 方法来保持不同系统的互操作性(Json 和 XML 响应):

[ServiceContract]
public interface IRestService
{
    [OperationContract(Name = "ConsultaDadosXml")]
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "ConsultaDados/xml?token={token}")]
    Dados ConsultaDadosXml(string token);

    [OperationContract(Name = "ConsultaDadosJson")]
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "ConsultaDados/json?token={token}")]
    Dados ConsultaDadosJson(string token);
}

问题是,当 DtNascimento 值带有来自数据库的良好值时,一切正常。当这个值在数据库上真的是 null 时,XML/JSON 响应没有 NASCIMENTO 标签,这是因为我们有 EmitDefaultValue = 。我可以将我的数据库设置为在发生这种情况时向我发送一个空值,但我的序列化对象在响应中带有一个 MinDate 值。

Xml版本:

<DADOS>
    <NASCIMENTO>1900-01-01T00:00:00</NASCIMENTO>
</DADOS>

Json版本:

{
    "NASCIMENTO": "/Date(-2208981600000-0200)/",
}

我真正需要的是当此值为 null 时在答案上显示一个空变量,因为 Web 服务上插入了其他系统试图解释这些值,因此最好的解决方案是保留空变量:

Xml版本:

<DADOS>
    <NASCIMENTO></NASCIMENTO>
</DADOS>

Json版本:

{
    "NASCIMENTO": "",
}

如有任何建议,我们将不胜感激。

感谢

里奥

您可以创建一个代理字符串值私有 属性,returns 一个 null DateTime? 值的空字符串,并将其序列化。它会生成以下格式的空元素:

<NASCIMENTO></NASCIMENTO>

XML standard定义为与<NASCIMENTO />具有相同的含义。

[DataContract(Name = "DADOS")]
public class Dados
{
    [IgnoreDataMember]
    public DateTime? DtNascimento { get; set; }

    [DataMember(EmitDefaultValue = false, Name = "NASCIMENTO")]
    string DtNascimentoString
    {
        get
        {
            if (DtNascimento == null)
                return string.Empty;
            return XmlConvert.ToString(DtNascimento.Value, XmlDateTimeSerializationMode.RoundtripKind);
        }
        set
        {
            if (string.IsNullOrEmpty(value))
                DtNascimento = null;
            else
                DtNascimento = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
        }
    }
}