6.12自定义内容转换器

创建于 2026 年 8 月 17 日约 1 分钟读完

在特定场景下,当框架内置的 IHttpContentConverter 内容转换器无法满足需求时,可以通过自定义 IHttpContentConverter 内容转换器来解决。

例如,为 Span<char> 类型添加内容转换器,可以通过实现 IHttpContentConverter 接口来实现自定义需求。

cs
public class SpanCharContentConverter : HttpContentConverterBase<Span<char>>{    /// <inheritdoc />    public override byte[]? Read(HttpContentConverterContext context, CancellationToken cancellationToken = default) =>        AsyncUtility.RunSync(() => ReadAsync(context, cancellationToken));    /// <inheritdoc />    public override async Task<Span<char>?> ReadAsync(HttpContentConverterContext context, CancellationToken cancellationToken = default)    {        var str = await context.ResponseMessage.Content.ReadAsStringAsync(cancellationToken);        return str.AsSpan();    }}

接下来,可以通过以下两种方式应用自定义内容转换器器:

  • 单次请求设置
cs
HttpRequestBuilder.Post("https://furion.net/")    .AddHttpContentConverters(() => [ new SpanCharContentConverter() ]);
  • 全局配置

Startup.csProgram.cs 文件中,配置并注册 HttpRemote 服务,以启用自定义内容转换器功能:

cs
services.AddHttpRemote(builder =>{    builder.AddHttpContentConverters(() => [ new SpanCharContentConverter() ]);});

以下示例展示了如何在发送 HTTP 远程请求时使用 SpanCharContentConverter 内容转换器:

使用 IHttpRemoteService 方式:

cs
// 单次请求添加var span = await httpRemoteService.SendAsAsync<Span<char>>(HttpRequestBuilder.Post("https://furion.net/")    .AddHttpContentConverters(() => [ new SpanCharContentConverter() ]));// 全局配置var span = await httpRemoteService.GetAsAsync<Span<char>>("https://furion.net/");

使用 IHttpContentConverterFactory 方式:

cs
public class YourService(IHttpContentConverterFactory httpContentConverterFactory)  // .NET8+ 支持主构造函数注入{    public async Task<Span<char>?> GetSpanAsync()    {        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://furion.net/");        using var httpClient = new HttpClient();        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);        // 调用 ReadAsync 方法将 HttpResponseMessage 对象转换为目标类型实例        var context = new HttpContentConverterContext(httpResponseMessage);        return await httpContentConverterFactory.GetConverter<Span<char>>(context).ReadAsync(context);    }}