网站首页 网站源码
using MessagePack;
using Microsoft.AspNetCore.Mvc.Formatters;
namespace Dpz.Core.WebApi.MessagePackFormatters;
/// <summary>
/// MVC output formatter.
/// </summary>
public class MessagePackOutputFormatter : OutputFormatter
{
readonly MessagePackSerializerOptions _options;
/// <summary>
/// ctor
/// </summary>
/// <param name="options">MessagePack 格式化选项</param>
/// <param name="mediaTypes">支持类型</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="options" /> or <paramref name="mediaTypes" /> is
/// <c>null</c>.
/// </exception>
/// <exception cref="T:System.ArgumentException"><paramref name="mediaTypes" /> collection is empty.</exception>
public MessagePackOutputFormatter(
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));
foreach (var mediaType in mediaTypes)
SupportedMediaTypes.Add(mediaType);
}
/// <inheritdoc />
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
var writer = context.HttpContext.Response.BodyWriter;
if (context.Object == null)
{
new MessagePackWriter(writer).WriteNil();
}
else
{
var objectType =
context.ObjectType is null || context.ObjectType == typeof(object)
? context.Object.GetType()
: context.ObjectType;
MessagePackSerializer.Serialize(
objectType,
writer,
context.Object,
_options,
context.HttpContext.RequestAborted
);
}
await writer.FlushAsync();
}
}
上述代码定义了一个名为 MessagePackOutputFormatter
的类,它是 ASP.NET Core 中的一个输出格式化器,用于将响应数据序列化为 MessagePack 格式。MessagePack 是一种高效的二进制序列化格式,常用于网络通信和数据存储。
以下是代码的主要功能和组成部分的详细解释:
MessagePackOutputFormatter
继承自 OutputFormatter
,这是 ASP.NET Core 中用于处理 HTTP 响应输出的基类。MessagePackSerializerOptions options
:用于配置 MessagePack 序列化的选项。ICollection<string> mediaTypes
:支持的媒体类型(如 "application/x-msgpack")。options
或 mediaTypes
为 null
,则抛出 ArgumentNullException
。mediaTypes
为空,则抛出 ArgumentException
。SupportedMediaTypes
集合中。OutputFormatter
的方法,用于将响应体写入 HTTP 响应。OutputFormatterWriteContext context
包含了响应的上下文信息。HttpContext.Response.BodyWriter
,用于写入响应体。context.Object
为 null
,则使用 MessagePackWriter
写入一个 nil
值。context.Object
不为 null
,则确定要序列化的对象类型。如果 context.ObjectType
为 null
或者是 object
类型,则使用 context.Object
的实际类型。MessagePackSerializer.Serialize
方法将对象序列化为 MessagePack 格式,并写入响应体。FlushAsync
方法确保所有数据都被写入响应。MessagePackOutputFormatter
类的主要功能是将 ASP.NET Core 的 HTTP 响应数据序列化为 MessagePack 格式,以便客户端能够以高效的二进制格式接收数据。它通过构造函数配置支持的媒体类型和序列化选项,并在 WriteResponseBodyAsync
方法中实现了具体的序列化逻辑。