6.3IHttpContentProcessorFactory 内容处理器工厂
创建于 2026 年 8 月 17 日约 1 分钟读完
IHttpContentProcessorFactory 内容处理器工厂负责根据原始请求的内容和类型,确定合适的 IHttpContentProcessor 内容处理器,并调用其 Process 方法来生成 HttpContent 实例。该工厂服务被配置为单例模式,以确保其在应用程序生命周期中的唯一性和稳定性。
如果未找到合适的 IHttpContentProcessor 内容处理器,将引发 InvalidOperationException 异常,异常信息如下:
No processor found that can handle the content type `application/pdf` and the provided raw content of type `System.Span`1[T]`. Please ensure that the correct content type is specified and that a suitable processor is registered.以下是使用 IHttpContentProcessorFactory 内容处理器工厂与 HttpClient 结合的示例,展示了如何通过其 Build 方法轻松构建合适的 HttpContent 内容。根据之前的章节说明,当内容类型为 application/json 时,将使用 StringContentProcessor 处理器,并生成 StringContent 实例。
public class YourService(IHttpContentProcessorFactory httpContentProcessorFactory) // .NET8+ 支持主构造函数注入{ public async Task<string> GetStringAsync() { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://furion.net/"); // 调用 Build 方法构建 HttpContent 实例,实例具体类型为 StringContent var httpContent = httpContentProcessorFactory.Build(new HttpContentProcessorContext(new { id = 1, name = "Furion" }, "application/json")); httpRequestMessage.Content = httpContent; using var httpClient = new HttpClient(); var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage); return await httpResponseMessage.Content.ReadAsStringAsync(); }}