dimanche 24 mai 2015

Custom serializer not working in Web API 2 for oData 4 when the URL contains $select

I implemented a custom serializer by inheriting ODataEntityTypeSerializer. The serializer sets the value of "MessageStateName" by converting "MessageState" to a BayStateEnum and getting the enum's name. It works well only except when the URL contains "$select". I debugged the code and found it was executed and entityInstanceContext.EntityInstance had the correct value, but entityInstanceContext.EdmModel, which was of type System.Web.OData.Query.Expressions.SelectExpandBinder.SelectSome, still had an empty "MessageStateName".

public class CustomEntitySerializer : ODataEntityTypeSerializer
{
    public CustomEntitySerializer(ODataSerializerProvider serializerProvider)
        : base(serializerProvider)
    {
    }
    public override ODataEntry CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)
    {
        if (entityInstanceContext.EntityInstance is SmartLinkInfoModel)
        {
            var smartLinkInfo = entityInstanceContext.EntityInstance as SmartLinkInfoModel;
            if (smartLinkInfo.ModemIMEI != null)
            {
                smartLinkInfo.ModemIMEIString = "0x" + string.Join(string.Empty, smartLinkInfo.ModemIMEI.Select(b => (b - 48).ToString()));
            }
            if (smartLinkInfo.SmartLinkHardwareId != null)
            {
                smartLinkInfo.SmartLinkHardwareIdString = "0x" + string.Join(string.Empty, smartLinkInfo.SmartLinkHardwareId.Select(b => b.ToString()));
            }
            if (smartLinkInfo.XbeeSourceId != null)
            {
                smartLinkInfo.XbeeSourceIdString = "0x" + string.Join(string.Empty, smartLinkInfo.XbeeSourceId.Select(b => b.ToString()));
            }
        }
        else if (entityInstanceContext.EntityInstance is BayMessageModel)
        {
            var bayMessage = entityInstanceContext.EntityInstance as BayMessageModel;
            bayMessage.MessageStateName = Enum.GetName(typeof(BayStateEnum), bayMessage.MessageState);
        }
        return base.CreateEntry(selectExpandNode, entityInstanceContext);
    }
}




Aucun commentaire:

Enregistrer un commentaire