当 URL 包含 $select 时,自定义序列化程序无法在 oData 4 的 Web API 2 中工作

问题描述 投票:0回答:1

我通过继承

ODataEntityTypeSerializer
实现了自定义序列化器。序列化器设置
MessageStateName by getting the name of 
BayStateEnum
from the value of
MessageState` 的值。

只有当 URL 包含

$select
时,它才能正常工作。我调试了代码,发现它被执行了,
entityInstanceContext.EntityInstance
有正确的值,但是类型为
entityInstanceContext.EdmModel
System.Web.OData.Query.Expressions.SelectExpandBinder.SelectSome<SmartComms.Archive.Api.Models.BayMessageModel>
仍然有一个空的
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);
    }
}
select serialization asp.net-web-api2 odata
1个回答
0
投票

您更改entityInstanceContext.EntityInstance的代码是正确的,但它不会改变select的结果,您可以看到

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

ODataEntityTypeSerializer
CreateStructuralProperty
方法中,您应该重写此方法,如果
structuralProperty.Name
MessageStateName
,则使用
(entityInstanceContext.EntityInstance as BayMessageModel).MessageStateName

© www.soinside.com 2019 - 2024. All rights reserved.