HttpClientFactory 是 .NET 推荐的客户端管理方式,解决资源泄漏和 DNS 更新问题;通过复用 HttpMessageHandler 避免 socket 耗尽,支持命名客户端、类型化客户端和 Polly 弹性策略;在 Program.cs 中注册客户端并配置默认值,使用 AddHttpClient 注册命名或类型化客户端,结合 Polly 实现重试、熔断等容错机制,合理设置 PooledConnectionLifetime 应对 DNS 变更,优先使用类型化客户端提升可测试性与代码组织性,由 DI 容器管理生命周期,避免手动 new HttpClient 或长期持有实例,正确使用可显著提升应用性能与稳定性。

虽然 HttpClient 实现了 IDisposable,但频繁创建和销毁会导致 Socket 耗尽,因为连接底层是基于 SocketsHttpHandler 的 TCP 连接,即使释放对象,连接仍可能保持 TIME_WAIT 状态一段时间。
HttpClientFactory 封装了实例的创建与生命周期管理,复用内部的 HttpMessageHandler,避免频繁创建连接,同时支持命名客户端、类型化客户端和 Polly 集成等高级功能。
适用于多个服务调用场景,通过名称区分不同配置的客户端。
在 Program.cs 或 Startup.cs 中注册:
builder.Services.AddHttpClient("github", client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
client.DefaultRequestHeaders.Add("User-Agent", "MyApp");
});
在控制器或服务中注入 IHttpClientFactory 并使用:
public class GitHubService
{
private readonly IHttpClientFactory _factory;
public GitHubService(IHttpClientFactory factory)
{
_factory = factory;
}
public async Task<string> GetOrgReposAsync()
{
var client = _factory.CreateClient("github");
var response = await client.GetStringAsync("/orgs/dotnet/repos");
return response;
}
}
将 HttpClient 封装在具体类中,提升可测试性和代码组织性。
定义一个类型化客户端:
public class WeatherService
{
private readonly HttpClient _client;
public WeatherService(HttpClient client)
{
_client = client;
_client.BaseAddress = new Uri("https://weather.api/");
}
public async Task<WeatherResponse> GetCurrentWeatherAsync(string city)
{
return await _client.GetFromJsonAsync<WeatherResponse>($"weather?city={city}");
}
}
注册服务:
builder.Services.AddHttpClient<WeatherService>();
在控制器中直接依赖注入:
[ApiController]
public class WeatherController : ControllerBase
{
private readonly WeatherService _weatherService;
public WeatherController(WeatherService weatherService)
{
_weatherService = weatherService;
}
[HttpGet("weather")]
public async Task<IActionResult> Get(string city)
{
var data = await _weatherService.GetCurrentWeatherAsync(city);
return Ok(data);
}
}
HttpClientFactory 可无缝集成 Polly,实现重试、熔断、超时等容错机制。
安装 NuGet 包:Polly 和 Polly.Extensions.Http
配置带有重试策略的客户端:
builder.Services.AddHttpClient<ResilientService>()
.AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(3),
TimeSpan.FromSeconds(5)
}));
上述策略会在遇到 HTTP 5xx、408 等错误时自动重试三次。
可以为所有客户端或特定客户端添加默认头、超时设置或日志记录。
builder.Services.AddHttpClient<LoggingClient>(client =>
{
client.Timeout = TimeSpan.FromSeconds(10);
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5), // 控制连接生命周期,应对 DNS 变更
MaxConnectionsPerServer = 100
});
.NET 自动集成 ILogger,可通过日志查看请求详情。
以上就是C# 如何使用 HttpClientFactory_C# HttpClientFactory 使用最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号