簡體   English   中英

URL包含$ select時,自定義序列化程序不適用於oData 4的Web API 2

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

我通過繼承ODataEntityTypeSerializer實現了自定義序列化程序。 序列化程序通過從“ MessageState”的值獲取BayStateEnum的名稱來設置“ MessageStateName”的值。 它僅在URL包含“ $ select”時有效。 我調試了代碼,發現它已執行,並且EntityInstanceContext.EntityInstance具有正確的值,但是類型為System.Web.OData.Query.Expressions.SelectExpandBinder.SelectSome的entityInstanceContext.EdmModel仍然具有空的“ 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);
    }
}

您更改entityInstanceContext.EntityInstance的代碼是正確的,但是它不會更改select的結果,您可以看到

object propertyValue = entityInstanceContext.GetPropertyValue(structuralProperty.Name);

ODataEntityTypeSerializerCreateStructuralProperty方法中,如果structuralProperty.NameMessageStateName ,則應重寫此方法,然后使用(entityInstanceContext.EntityInstance as BayMessageModel).MessageStateName

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM