6.16HttpRemoteOptions 配置选项

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

使用 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.RequestBuilderConfigurator = null;    // 默认为 null    });

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

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