6.12Custom Content Converter
In certain scenarios, when the framework's built-in IHttpContentConverter content converter cannot meet your needs, you can solve this by customizing the IHttpContentConverter content converter.
For example, to add a content converter for the Span<char> type, you can implement custom requirements by implementing the IHttpContentConverter interface.
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(); }}Next, you can apply the custom content converter in the following two ways:
- Per-request configuration:
HttpRequestBuilder.Post("https://furion.net/") .AddHttpContentConverters(() => [ new SpanCharContentConverter() ]);- Global configuration:
In the Startup.cs or Program.cs file, configure and register the HttpRemote service to enable the custom content converter functionality:
services.AddHttpRemote(builder =>{ builder.AddHttpContentConverters(() => [ new SpanCharContentConverter() ]);});The following example shows how to use the SpanCharContentConverter content converter when sending an HTTP remote request:
Using the IHttpRemoteService approach:
// Add for a single requestvar span = await httpRemoteService.SendAsAsync<Span<char>>(HttpRequestBuilder.Post("https://furion.net/") .AddHttpContentConverters(() => [ new SpanCharContentConverter() ]));// Global configurationvar span = await httpRemoteService.GetAsAsync<Span<char>>("https://furion.net/");Using the IHttpContentConverterFactory approach:
public class YourService(IHttpContentConverterFactory httpContentConverterFactory) // .NET8+ supports primary constructor injection{ 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); // Call the ReadAsync method to convert the HttpResponseMessage object into a target type instance var context = new HttpContentConverterContext(httpResponseMessage); return await httpContentConverterFactory.GetConverter<Span<char>>(context).ReadAsync(context); }}