另一個常見的需求是根據不同的服務介面建立不同的HttpClient例項。為了實現這一點,ASP.NET Core提供了Typed HttpClient的支援。
下面是使用Typed HttpClient的示例程式碼:
public interface IExampleService
{
Task<string> GetData();
}
public class ExampleService : IExampleService
{
private readonly HttpClient _httpClient;
public ExampleService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetData()
{
HttpResponseMessage response = await _httpClient.GetAsync("");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
配置依賴注入:
builder.Services.AddHttpClient<IExampleService, ExampleService>(client =>
{
client.BaseAddress = new Uri("https://www.baidu.com/");
});
在控制器中注入IExampleService:
private readonly ILogger<WeatherForecastController> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IExampleService _exampleService;
public WeatherForecastController(ILogger<WeatherForecastController> logger,
IHttpClientFactory httpClientFactory,
IExampleService exampleService)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
_exampleService = exampleService;
}
在上面的示例中,我們首先定義了一個IExampleService介面,該介面定義了與外部服務互動的方法。然後,我們實現了ExampleService類,並在建構函式中注入了HttpClient例項。
最後,我們使用AddHttpClient方法的另一個過載版本,並透過泛型引數指定了服務介面和實現類的關聯關係。在配置HttpClient的回撥中,我們可以進行相應的配置,如設定BaseAddress等