OData WebApi V4 .net-自定义序列化

adi*_*ben 5 .net c# asp.net serialization odata

我需要创建一个序列化器来支持以下所有任务:

  1. 删除空属性
  2. 删除空列表

我注意到的语法ODataMediaTypeFormatter已更改。

我在将我的Serialzation提供程序添加到管道时遇到了麻烦。

这是我尝试过的:

在WebApiConfig.cs上:

var odataFormatters = ODataMediaTypeFormatters.Create();
odataFormatters.Add(new MyDataMediaTypeFormatter());
config.Formatters.InsertRange(0, odataFormatters);
Run Code Online (Sandbox Code Playgroud)

另外,我创建了以下内容Odatameditatypeformatter

public class MyODataMediaTypeFormatter : ODataMediaTypeFormatter
{
    static IEnumerable<ODataPayloadKind> payloadKinds = new List<ODataPayloadKind>
    {

        ODataPayloadKind.Asynchronous,
        ODataPayloadKind.Batch,
        ODataPayloadKind.BinaryValue,
        ODataPayloadKind.Collection,
        ODataPayloadKind.EntityReferenceLink,
        ODataPayloadKind.EntityReferenceLinks,
        ODataPayloadKind.Error,
        ODataPayloadKind.Delta,
        ODataPayloadKind.IndividualProperty,
        ODataPayloadKind.MetadataDocument,
        ODataPayloadKind.Parameter,
        ODataPayloadKind.Resource,
        ODataPayloadKind.ServiceDocument,
        ODataPayloadKind.Unsupported,
        ODataPayloadKind.Value
    };

    public MyODataMediaTypeFormatter() : base(payloadKinds)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

当前,我检查了所有基本方法,在向我的OData控制器创建Get / Post请求时,它们似乎都没有碰到断点。

有人设法在新版本的Microsoft.Aspnet.OData 7.0.1上做到这一点吗?

adi*_*ben 5

我找到了解决方案。在新版本上,所有序列化和反序列化自定义只能通过依赖项注入启用。

首先我们需要重写序列化提供程序:

/// <summary>
/// Provider that selects the IgnoreNullEntityPropertiesSerializer that omits null properties on resources from the response
/// </summary>
public class MySerializerProvider : DefaultODataSerializerProvider
{
    private readonly IgnoreNullsSerializer _propertiesSerializer;
    private readonly IgnoreEmptyListsResourceSetSerializer _ignoreEmptyListsSerializer;
    private readonly IgnoreEmptyListsCollectionSerializer _ignoreEmptyListsCollectionSerializer;

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="rootContainer"></param>
    public MySerializerProvider(IServiceProvider rootContainer)
        : base(rootContainer)
    {
        _ignoreEmptyListsSerializer = new IgnoreEmptyListsResourceSetSerializer(this);
        _propertiesSerializer = new IgnoreNullsSerializer(this);
        _ignoreEmptyListsCollectionSerializer = new IgnoreEmptyListsCollectionSerializer(this);
    }

    /// <summary>
    /// Mark edmtype to apply the serialization on
    /// </summary>
    /// <param name="edmType"></param>
    /// <returns></returns>
    public override ODataEdmTypeSerializer GetEdmTypeSerializer(Microsoft.OData.Edm.IEdmTypeReference edmType)
    {
        // Support for Entity types AND Complex types
        if (edmType.Definition.TypeKind == EdmTypeKind.Entity || edmType.Definition.TypeKind == EdmTypeKind.Complex)
        {
            return _propertiesSerializer;
        }
        if (edmType.Definition.TypeKind == EdmTypeKind.Collection)
        {
            if(edmType.Definition.AsElementType().IsDecimal() || edmType.Definition.AsElementType().IsString())
                return _ignoreEmptyListsCollectionSerializer;

            return _ignoreEmptyListsSerializer;
        }            

        var result = base.GetEdmTypeSerializer(edmType);
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要根据要覆盖其行为的 EdmType 覆盖不同的序列化程序。

我添加了一个序列化器的示例,该序列化器根据请求中的“HideEmptyLists”标头忽略来自实体的空列表...

/// <inheritdoc />
/// <summary>
/// OData Entity Serializer that omits empty listss properties from the response
/// </summary>
public class IgnoreEmptyListsResourceSetSerializer : ODataResourceSetSerializer
{
    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="provider"></param>
    public IgnoreEmptyListsResourceSetSerializer(ODataSerializerProvider provider) : base(provider) { }


    /// <inheritdoc />
    public override void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer,
        ODataSerializerContext writeContext)
    {
        var shouldHideEmptyLists = writeContext.Request.GetHeader("HideEmptyLists");
        if (shouldHideEmptyLists != null)
        {     
            IEnumerable enumerable = graph as IEnumerable; // Data to serialize

            if (enumerable.IsNullOrEmpty())
            {
                return;
                //ignore
            }
        }

        base.WriteObjectInline(graph, expectedType, writer, writeContext);
    }

}
Run Code Online (Sandbox Code Playgroud)

还有另一个忽略集合的空列表......

/// <inheritdoc />
/// <summary>
/// OData Entity Serilizer that omits null properties from the response
/// </summary>
public class IgnoreEmptyListsCollectionSerializer : ODataCollectionSerializer
{
    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="provider"></param>
    public IgnoreEmptyListsCollectionSerializer(ODataSerializerProvider provider)
        : base(provider) { }


    /// <summary>
    /// Creates an <see cref="ODataCollectionValue"/> for the enumerable represented by <paramref name="enumerable"/>.
    /// </summary>
    /// <param name="enumerable">The value of the collection to be created.</param>
    /// <param name="elementType">The element EDM type of the collection.</param>
    /// <param name="writeContext">The serializer context to be used while creating the collection.</param>
    /// <returns>The created <see cref="ODataCollectionValue"/>.</returns>
    public override ODataCollectionValue CreateODataCollectionValue(IEnumerable enumerable, IEdmTypeReference elementType,
        ODataSerializerContext writeContext)
    {

        var shouldHideEmptyLists = writeContext.Request.GetHeader("HideEmptyLists");
        if (shouldHideEmptyLists != null)
        {
            if (enumerable.IsNullOrEmpty())
            {
                return null;
                //ignore
            }
        }

        var result = base.CreateODataCollectionValue(enumerable, elementType, writeContext);            
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,我将展示如何将序列化提供程序注入到我们的 OData 管道中:

        config.MapODataServiceRoute(odata, odata, builder => builder
            .AddService<ODataSerializerProvider>(ServiceLifetime.Scoped, sp => new MySerializerProvider(sp)));
Run Code Online (Sandbox Code Playgroud)

这应该结束了。干杯。