自定义OData DateTime输出

时间:2016-12-07 21:05:09

标签: asp.net-mvc datetime asp.net-web-api odata

我有以下型号:

public class PersonModel {
    public int Id {get; set;}
    public DateTime BirthDay {get;set;}
    ....
}

当获取请求时,OData返回DateTimeOffset而不是DateTime。例如,请求' / api / rest / people / 1'返回:

{
 id:1,
 birthDay: "12/7/2016 8:57:58 PM +00:00"
 ....
}

我想要什么?我只需要返回日期值" 12/7/2016"。我试图实现一个自定义的ODataPayloadValue转换器,但OData似乎并不理解' DateTime'类型。

 public override object ConvertToPayloadValue(object value, IEdmTypeReference edmTypeReference)
    {
        /// There isn't a IEdmtypeRefere.IsDateTime 
        /// Thus OData always think that DateTime is equals to DateTimeOffset
        if (value is DateTime)
        {
            ///Do some stuff here.
        }

        return base.ConvertToPayloadValue(value, edmTypeReference);
    }

2 个答案:

答案 0 :(得分:0)

最简单的方法 - 像这样扩展你的模型:

public class PersonModel {
    public int Id {get; set;}
    public DateTime BirthDay {get;set;}
    // add this property and you get it. You can rename it if you want
    public string BirthDate {get {return this.BirthDay.ToShourtDateString(); }}
    ....
}

答案 1 :(得分:0)

在做了一些研究之后,我发现有一种方法可以通过实现两个类来实现我想要的目标:

 // A custom serializer provider to inject the AnnotatingEntitySerializer.
public class CustomODataSerializerProvider : DefaultODataSerializerProvider
{
    private AnnotatingEntitySerializer _annotatingEntitySerializer;

    public CustomODataSerializerProvider()
    {
        _annotatingEntitySerializer = new AnnotatingEntitySerializer(this);
    }

    public override ODataEdmTypeSerializer GetEdmTypeSerializer(IEdmTypeReference edmType)
    {
        if (edmType.IsEntity())
        {
            return _annotatingEntitySerializer;
        }

        return base.GetEdmTypeSerializer(edmType);
    }
}


// A custom entity serializer that adds the score annotation to document entries.
public class AnnotatingEntitySerializer : ODataEntityTypeSerializer
{
    public AnnotatingEntitySerializer(ODataSerializerProvider serializerProvider)
        : base(serializerProvider)
    {
    }

    public override ODataEntry CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)
    {
        ODataEntry entry = base.CreateEntry(selectExpandNode, entityInstanceContext);

        PersonModel person = entityInstanceContext.EntityInstance as PersonModel;
        var property = entry.Properties.Where(x => x.Name == "birthDate").FirstOrDefault();
        property.Value = ((DateTimeOffset)property.Value).DateTime.ToShortDateString();


        return entry;
    }
}