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 @   一个人走在路上  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示