6.13Custom Generic Content Converter
Updated on Aug 20, 2026~2 min read
In addition to concrete types, the framework also supports the conversion of generic content. For example, define the following generic converter:
public class YourGenericClassContentConverter<T> : HttpContentConverterBase<YourGenericClass<T?>>{ /// <inheritdoc /> public override YourGenericClass<T?>? Read(HttpContentConverterContext context, CancellationToken cancellationToken = default) { // Implement the synchronous conversion logic } /// <inheritdoc /> public override Task<YourGenericClass<T?>?> ReadAsync(HttpContentConverterContext context, CancellationToken cancellationToken = default) { // Implement the asynchronous conversion logic }}Next, in the Startup.cs or Program.cs file, configure and register the HttpRemote service to enable the custom generic content converter functionality:
services.AddHttpRemote(builder =>{ builder.AddGenericHttpContentConverters(() => [ new(typeof(YourGenericClass<>), typeArgs => (IHttpContentConverter)Activator.CreateInstance(typeof(YourGenericClassContentConverter<>).MakeGenericType(typeArgs[0]))!) ]);});The following example shows how to use the YourGenericClassContentConverter content converter when sending an HTTP remote request:
Using the IHttpRemoteService approach:
var str = await httpRemoteService.GetAsAsync<YourGenericClass<string>>("https://furion.net/");Using the IHttpContentConverterFactory approach:
public class YourService(IHttpContentConverterFactory httpContentConverterFactory) // .NET8+ supports primary constructor injection{ public async Task<YourGenericClass<string>?> GetStringAsync() { 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<YourGenericClass<string>>(context).ReadAsync(context); }}