OData WebApi V4 .net-自定义序列化 [英] OData WebApi V4 .net - Custom Serialization
问题描述
我需要创建一个序列化器来支持以下所有任务:
I need to create a Serializer to support all of the following tasks:
- 删除空属性
- 删除空列表
我注意到ODataMediaTypeFormatter
的语法已更改.
I noticed the Syntax of the ODataMediaTypeFormatter
has been changed.
我在将我的Serialzation提供程序添加到管道时遇到了麻烦.
And I'm having trouble adding my Serialzation provider to the pipe.
这是我尝试过的:
在WebApiConfig.cs上:
On WebApiConfig.cs:
var odataFormatters = ODataMediaTypeFormatters.Create();
odataFormatters.Add(new MyDataMediaTypeFormatter());
config.Formatters.InsertRange(0, odataFormatters);
另外,我创建了以下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)
{
}
}
当前,我检查了所有基本方法,在向我的OData控制器创建Get/Post请求时,似乎没有一个碰到断点.
Currently I checked all the base methods and none of them seems to hit the breakpoint while creating a Get/Post request to my OData controllers.
有没有人设法在新版本的Microsoft.Aspnet.OData 7.0.1上做到这一点?
Any one managed to do it on the new version of Microsoft.Aspnet.OData 7.0.1?
推荐答案
我找到了解决方案. 在新版本上,只有通过依赖注入才能启用所有序列化和反序列化定制.
I found the solution. On the new versions all the serialization and deserialization customization is enabled only through dependency injection.
首先,我们需要重写序列化提供程序:
First we need to override the serialization provider:
/// <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覆盖不同的序列化器.
You might need to override different serializers based on the EdmType you want to override it's behavior.
我要添加一个序列化程序的示例,该序列化程序将根据请求中的"HideEmptyLists"标头忽略来自实体的空列表...
I'm adding an example of a serializer that ignore empty lists from entities based on "HideEmptyLists" header on the request...
/// <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);
}
}
另一个忽略集合的空列表...
And another one to ignore empty list for collections...
/// <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管道:
And to finalize I'll show how to inject the Serialization Provider into our OData pipeline:
config.MapODataServiceRoute(odata, odata, builder => builder
.AddService<ODataSerializerProvider>(ServiceLifetime.Scoped, sp => new MySerializerProvider(sp)));
那应该把它包起来. 欢呼.
That should wrap it up. cheers.
这篇关于OData WebApi V4 .net-自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!