2017-10-17 176 views
0

我可以在正在使用OData序列化的模型上放置一個屬性,並根據它選擇序列化嗎?Odata 4 - 如何序列化基於ODataResourceSerializer中的自定義屬性的屬性

我已經成功擴展了ODataResourceSerializer,並重寫了CreateStructuralProperty。這使我能夠檢查一個屬性的名稱,並選擇是否序列化它。

下面是我已經設置(這是工作)的一個總結。這是我在登記啓動服務...

private static void ConfigureODataServices(IContainerBuilder builder) 
    { 
     // add custom odata serializer 
     builder.AddService<ODataSerializerProvider>(Singleton, s => new CustomODataSerializerProvider(s)); 
    } 

這是我的自定義格式,在那裏我目前只使用屬性名稱來選擇是否要序列化這個屬性:

public class CustomODataSerializerProvider : DefaultODataSerializerProvider 
{ 
    private AnnotatingEntitySerializer _annotatingEntitySerializer; 

    public CustomODataSerializerProvider(IServiceProvider container) : base(container) 
    { 
     _annotatingEntitySerializer = new AnnotatingEntitySerializer(this); 
    } 

    public override ODataEdmTypeSerializer GetEdmTypeSerializer(IEdmTypeReference edmType) 
    { 
     if (edmType.Definition.TypeKind == EdmTypeKind.Entity) 
      return new AnnotatingEntitySerializer(this); 

     return base.GetEdmTypeSerializer(edmType); 
    } 
} 


public class AnnotatingEntitySerializer : ODataResourceSerializer 
{ 
    public AnnotatingEntitySerializer(ODataSerializerProvider serializerProvider) 
     : base(serializerProvider) 
    { 
    } 

    public override Microsoft.OData.ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, ResourceContext resourceContext) 
    { 
     Microsoft.OData.ODataProperty property = base.CreateStructuralProperty(structuralProperty, resourceContext); 

     if (resourceContext.StructuredType.FullTypeName() == typeof(Site).FullName) 
     { 
      if (property.Name == "IsDeleted") // NOTE: here, rather than checking for the property name, I want to check if it has an attribute of "ExcludeMe" 
      { 
       return null; 
      } 
     } 

     return property; 
    } 

    public override void AppendDynamicProperties(ODataResource resource, System.Web.OData.Formatter.Serialization.SelectExpandNode selectExpandNode, 
     ResourceContext resourceContext) 
    { 
     base.AppendDynamicProperties(resource, selectExpandNode, resourceContext); 
    } 
} 

但當然,我想用一個屬性來選擇無論是序列化,而不是硬編碼的屬性名稱。可能?謝謝。

回答