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

时间:2018-11-05 09:16:23

标签: c# asp.net .net serialization odata

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

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

我注意到Rest API的语法已更改。

我在将我的Serialzation提供程序添加到管道时遇到问题。

这是我尝试过的:

在WebApiConfig.cs上:

ODataMediaTypeFormatter

另外,我创建了以下var odataFormatters = ODataMediaTypeFormatters.Create(); odataFormatters.Add(new MyDataMediaTypeFormatter()); config.Formatters.InsertRange(0, odataFormatters);

Odatameditatypeformatter

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

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

2 个答案:

答案 0 :(得分:2)

谢谢,但是端点路由的解决方案有点不同,我在这里发布给感兴趣的人:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.EnableDependencyInjection();
    endpoints.MaxTop(5000).SkipToken().Select().Filter().OrderBy().Expand().Count();
    //endpoints.MapODataRoute("odata", "odata", GetEdmModel(context));
    endpoints.MapODataRoute("odata", "odata",
        builder =>
        {
            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(IEdmModel), serviceProvider => GetEdmModel(context));
            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(IEnumerable<IODataRoutingConvention>), serviceProvider => ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata",endpoints.ServiceProvider));
            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(ODataUriResolver), serviceProvider => new StringAsEnumResolver());
            builder.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(ODataSerializerProvider), serviceProvider => new MySerializerProvider(serviceProvider));
        });
}

答案 1 :(得分:0)

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

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

/// <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;
    }
}

您可能需要根据要覆盖其行为的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);
    }

}

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

/// <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;
    }
}

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

        config.MapODataServiceRoute(odata, odata, builder => builder
            .AddService<ODataSerializerProvider>(ServiceLifetime.Scoped, sp => new MySerializerProvider(sp)));

那应该把它包起来。 欢呼。