Asp.Net Core中Typed HttpClient高级用法

另一个常见的需求是根据不同的服务接口创建不同的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等

posted @ 2024-08-28 11:16  一个人走在路上  阅读(44)  评论(0)    收藏  举报