HttpClient 统一配置
AgileLabs.HttpClients.HttpClientServiceRegister 提供一致的 HttpClientFactory 配置,解决代理、压缩、Cookie 等问题。
注册方式
框架会自动扫描实现 IServiceRegister 的类型,因此引入 AgileLabs.WebApp 包即可自动生效。若需单独使用,可在 ConfigureServices 中显式调用:
services.AddHttpClient(NamedHttpClients.Default)
.ConfigurePrimaryHttpMessageHandler(...);
默认客户端
| 名称 | 说明 |
|---|---|
NamedHttpClients.Default |
不带 Cookie,默认启用 gzip/deflate/br 自动解压。 |
NamedHttpClients.WithCookie |
开启 Cookie 容器,用于需要会话的请求。 |
HttpClient(Transient) |
直接注入时返回 Default 客户端,并附加 Accept-Encoding 头。 |
Handler 配置
UseCookies:默认false,防止在多线程场景中意外共享 Cookie。AllowAutoRedirect:true,跟随 30x 重定向。AutomaticDecompression:GZip、Deflate、Brotli。- 代理支持:读取配置
WebProxy(http://user:pwd@proxy:8080),自动填充凭证。
使用示例
public class RemoteWeatherService
{
private readonly HttpClient _httpClient;
public RemoteWeatherService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetAsync(string city)
{
return await _httpClient.GetStringAsync($"https://api.example.com/weather?city={city}");
}
}
在 Program 中只需注册 RemoteWeatherService,框架会自动提供配置良好的 HttpClient。
下一步:了解 请求 Session 与 依赖注入策略。