6.6添加 Protobuf 支持
创建于 2026 年 8 月 17 日约 2 分钟读完
Protobuf(Protocol Buffers)是 Google 开发的一种语言中立、平台中立、可扩展的序列化结构数据格式,用于通信协议、数据存储等。
要在项目中启用 Protobuf 支持,请按照以下步骤操作:
- 安装
protobuf-net包:
dotnet add protobuf-net- 添加
ProtobufContentProcessor内容处理器:
public class ProtobufContentProcessor : HttpContentProcessorBase{ /// <inheritdoc /> public override bool CanProcess(HttpContentProcessorContext context) => context.ContentType == "application/x-protobuf"; /// <inheritdoc /> public override HttpContent? Process(HttpContentProcessorContext context) { // 尝试解析 HttpContent 类型 if (TryProcess(context, out var httpContent)) { return httpContent; } byte[] content; if (context.RawContent is byte[] bytes) { content = bytes; } else { // 将原始请求内容转换为字节数组 using var ms = new MemoryStream(); Serializer.Serialize(ms, context.RawContent); content = ms.ToArray(); } // 初始化 ByteArrayContent 实例 var byteArrayContent = new ByteArrayContent(content); byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue(context.ContentType) { CharSet = context.Encoding?.WebName }; return byteArrayContent; }}- 应用
ProtobufContentProcessor内容处理器:
- 单次请求设置:
HttpRequestBuilder.Post("https://furion.net/") .AddHttpContentProcessors(() => [ new ProtobufContentProcessor() ]) .SetContent(new MyProtobufMessage { Id = 1, Name = "Furion" }, "application/x-protobuf");- 全局配置:
在 Startup.cs 或 Program.cs 文件中,配置并注册 HttpRemote 服务,以启用 ProtobufContentProcessor 内容处理器功能:
services.AddHttpRemote(builder =>{ builder.AddHttpContentProcessors(() => [ new ProtobufContentProcessor() ]);});这样可以在项目中通过 HTTP 远程请求发送 application/x-protobuf 格式的数据。