网站首页 网站源码
using MessagePack;
using Microsoft.AspNetCore.Mvc.Formatters;
namespace Dpz.Core.WebApi.MessagePackFormatters;
/// <summary>
/// formatter
/// </summary>
public class MessagePackInputFormatter : InputFormatter
{
private readonly MessagePackSerializerOptions _options;
private readonly SerializableTypesCache _serializableTypesCache;
/// <summary>
/// ctor
/// </summary>
/// <param name="options"></param>
/// <param name="mediaTypes"></param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public MessagePackInputFormatter(
MessagePackSerializerOptions options,
ICollection<string> mediaTypes
)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
if (mediaTypes == null)
throw new ArgumentNullException(nameof(mediaTypes));
if (mediaTypes.Count == 0)
throw new ArgumentException("Media type must be specified.", nameof(mediaTypes));
_serializableTypesCache = new SerializableTypesCache(options.Resolver);
foreach (var mediaType in mediaTypes)
{
SupportedMediaTypes.Add(mediaType);
}
}
/// <inheritdoc />
public override async Task<InputFormatterResult> ReadRequestBodyAsync(
InputFormatterContext context
)
{
var httpContext = context.HttpContext;
var result = await MessagePackSerializer
.DeserializeAsync(
context.ModelType,
httpContext.Request.Body,
_options,
httpContext.RequestAborted
);
return await InputFormatterResult.SuccessAsync(result);
}
/// <inheritdoc />
/// <exception cref="T:System.ArgumentNullException"><paramref name="type" /> is <c>null</c>.</exception>
protected override bool CanReadType(Type type)
{
return _serializableTypesCache.CanSerialize(type);
}
}
上述代码定义了一个名为 MessagePackInputFormatter
的类,它是 ASP.NET Core 中的一个输入格式化器(Input Formatter)。这个格式化器的主要功能是处理 HTTP 请求中的 MessagePack 格式的数据,并将其反序列化为 C# 对象。以下是代码的详细解释:
MessagePackInputFormatter
继承自 InputFormatter
,这是 ASP.NET Core 中用于处理请求体的基类。MessagePack
库来进行序列化和反序列化操作。MessagePackSerializerOptions options
:用于配置 MessagePack 序列化的选项。ICollection<string> mediaTypes
:支持的媒体类型集合(例如 "application/x-msgpack")。options
和 mediaTypes
是否为 null,并确保 mediaTypes
至少包含一个元素。SerializableTypesCache
来缓存可序列化的类型,以提高性能。SupportedMediaTypes
集合中,以便 ASP.NET Core 知道该格式化器支持哪些媒体类型。InputFormatter
的抽象方法,用于读取请求体并将其反序列化为指定的模型类型。MessagePackSerializer.DeserializeAsync
方法从请求的 Body 中异步读取数据,并将其反序列化为 context.ModelType
指定的类型。InputFormatterResult.SuccessAsync(result)
,其中 result
是反序列化后的对象。_serializableTypesCache.CanSerialize(type)
来判断该类型是否可以被序列化(即是否支持 MessagePack 格式)。MessagePackInputFormatter
类的主要功能是支持将 HTTP 请求中的 MessagePack 数据反序列化为 C# 对象。它通过构造函数配置支持的媒体类型和序列化选项,并实现了读取请求体和类型检查的逻辑。这使得 ASP.NET Core 应用程序能够处理 MessagePack 格式的数据,提供了一种高效的序列化和反序列化机制。