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等
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效