6.5IHttpRemoteService 服务

IHttpRemoteService 是一个用于发送 HTTP 远程请求的入口服务,它构成了 HTTP 远程请求模块的核心。简而言之,当需要发送 HTTP 远程请求时,应使用已注入的 IHttpRemoteService 服务。该服务默认以单例模式注册,因此可以在任何生存周期的服务中安全地使用。

IHttpRemoteService 服务 ✨#

IHttpRemoteService 是一个用于发送 HTTP 远程请求的入口服务,它构成了 HTTP 远程请求模块的核心。简而言之,当需要发送 HTTP 远程请求时,应使用已注入的 IHttpRemoteService 服务。该服务默认以单例模式注册,因此可以在任何生存周期的服务中安全地使用。

在使用 IHttpRemoteService 服务前,需在 Startup.csProgram.cs 文件中注册并配置 HttpRemote 服务。

cs
// 在 Startup.cs 中注册:services.AddHttpRemote();// 在 Program.cs 中,注册方式如下:// builder.Services.AddHttpRemote();

随后,在您的服务、控制器或任何支持依赖注入的类中,注入 IHttpRemoteService 服务。

cs
public class YourService{    private readonly IHttpRemoteService _httpRemoteService;    public YourService(IHttpRemoteService httpRemoteService)    {        _httpRemoteService = httpRemoteService;    }}

若您使用的是 .NET 8 及以上版本时,可通过主构造函数注入简化代码:

cs
public class YourService(IHttpRemoteService httpRemoteService){    // 使用 httpRemoteService 变量}

或者,您也可以在特定方法中按需注入:

cs
public class YourService{    public Task<string> GetResource([FromServices] IHttpRemoteService httpRemoteService)    {        // 您的代码逻辑    }}

HttpRemoteBuilder 构建器#

HttpRemoteBuilder 是一个构建器,用于配置和构建 IHttpRemoteService 服务所需的所有设置。在应用启动时,通常通过调用 services.AddHttpRemote 方法来指定这些配置。

以下展示了 HttpRemoteBuilder 提供的所有配置功能:

cs
services.AddHttpRemote(builder =>{    // 添加自定义内容处理器    builder.AddHttpContentProcessors(() => [ new CustomStringContentProcessor() ]);    // 添加自定义内容转换器    builder.AddHttpContentConverters(() => [ new SpanCharContentConverter() ]);    // 添加自定义泛型内容转换器    builder.AddGenericHttpContentConverters(() => [ new(typeof(IAsyncEnumerable<>), typeArgs => (IHttpContentConverter)Activator.CreateInstance(typeof(AsyncEnumerableContentConverter<>).MakeGenericType(typeArgs[0]))!) ]);    // 设置自定义对象内容转换器工厂    builder.UseObjectContentConverterFactory<CustomObjectContentConverterFactory>();    builder.UseObjectContentConverterFactory(typeof(CustomObjectContentConverterFactory));    // 添加 HTTP 声明式服务    builder.AddHttpDeclarative<IHttpService>();    builder.AddHttpDeclarative(typeof(IHttpService));   // 通过 requireIHttpDeclarative 参数,支持注册无需实现 IHttpDeclarative 接口的声明式代理    // 批量添加 HTTP 声明式服务    builder.AddHttpDeclaratives([typeof(IHttpService), typeof(IHttpService2), ...]);    // 扫描程序集批量添加 HTTP 声明式服务    builder.AddHttpDeclarativesFromAssemblies([ assembly1, assembly2, ... ]);  // 若使用 Furion 框架可直接设置 App.Assemblies    // 添加自定义 HTTP 声明式提取器    builder.AddHttpDeclarativeExtractors(() => [ new AcceptDeclarativeExtractor() ]);    // 扫描程序集批量添加 HTTP 声明式提取器    builder.AddHttpDeclarativeExtractorsFromAssemblies([ assembly1, assembly2, ... ]); // 若使用 Furion 框架可直接设置 App.Assemblies    // 添加 HTTP 请求管道处理器服务    builder.AddPipelineHandler<CustomHttpRequestPipelineHandler>();    builder.AddPipelineHandler(typeof(CustomHttpRequestPipelineHandler));    // 设置自定义日志服务,可通过继承 HttpRemoteLoggerBase 实现    builder.UseLogger<CustomHttpRemoteLogger>();    builder.UseLogger(typeof(CustomHttpRemoteLogger));});

HttpRemoteOptions 配置选项#

使用 services.AddHttpRemote() 方法添加 HTTP 远程请求服务时,会返回一个 IHttpRemoteBuilder 实例。通过该实例,可以访问并配置 HttpRemoteOptions,这些配置包括默认请求内容类型、JSON 序列化设置等属性:

cs
services.AddHttpRemote(builder => {})    .ConfigureOptions(options =>    {        // 配置默认的请求内容类型        options.DefaultContentType = "text/plain";  // 推荐配置为 "application/json"        // 设置文件下载的默认保存路径        options.DefaultFileDownloadDirectory = @"C:\Workspaces\";        // 设置请求分析工具日志级别,默认 Warning        options.ProfilerLogLevel = LogLevel.Warning;        // 设置指示请求是否应遵循重定向响应,默认 true        options.AllowAutoRedirect = true;        // 设置请求所遵循的最大重定向数,默认 50 次        options.MaximumAutomaticRedirections = 50;        // 设置回退请求基地址,当未配置 HttpClient 的 BaseAddress 且请求地址为相对地址时有效        options.FallbackBaseAddress = new Uri("https://localhost:5000");        // 自定义 JSON 序列化选项        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;        // 设置用于替换 URL 地址中配置模板参数的提供源        options.Configuration = builder.Configuration;  // 若使用 Furion 框架可直接设置 App.Configuration        // 设置 URL 参数格式化程序        options.UrlParameterFormatter = new UrlParameterFormatter();        // 日志服务或控制台输出不可用时的备用日志输出委托        options.FallbackLogger = Console.WriteLine; // 可替换为 Debug.WriteLine        // 设置 HttpRequestBuilder 统一配置器        options.HttpRequestBuilderConfigurator = null;    // 默认为 null    });

ConfigureOptions 方法允许对 HTTP 远程请求服务进行更多自定义配置,例如调整 JSON 序列化行为等。此外,ConfigureOptions 还提供了支持服务解析的重载方法。示例如下:

cs
services.AddHttpRemote(builder => {})    .ConfigureOptions((options, serviceProvider) =>    {        // 解析所需服务        var yourService = serviceProvider.GetRequiredService<IYourService>();        // 其他配置代码    });

统一配置 HttpClient 客户端#

在应用项目开发中,通常需要对所有的 HttpClient 客户端实例进行统一配置。为此,框架提供了 ConfigureHttpClientDefaults 方法,支持一键配置:

cs
services.ConfigureHttpClientDefaults(clientBuilder =>{    clientBuilder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler());});// 或者使用 IHttpRemoteBuilder 扩展方法进行一键配置services.AddHttpRemote()    .ConfigureHttpClientDefaults(clientBuilder =>    {        clientBuilder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler());    });

通过这种方式,可以轻松地为所有 HttpClient 实例设置默认的 HttpMessageHandler,确保配置的一致性和可维护性。