public class HomeController : Controller { private IHttpClientFactory _httpClientFactory; private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory) { _logger = logger; _httpClientFactory = httpClientFactory; } }
在Action中挪用HttpClient要通过利用IHttpClientFactory建设HttpClient,应该挪用CreateClient要领。一旦HttpClient实例可用,就可以在HomeController类的index要领中利用以下代码来挪用ValuesController类的Get要领。
public async Task<IActionResult> Index() { HttpClient httpClient = _httpClientFactory.CreateClient(); httpClient.BaseAddress = new Uri("http://localhost:1810/"); var response = await httpClient.GetAsync("/api/values"); string str = await response.Content.ReadAsStringAsync(); List<string> data = JsonSerializer.Deserialize<List<string>>(str); return View(data); }
利用IHttpClientFactory在ASP.NET Core中建设和打点HttpClient实例有几种要领可以在应用措施中利用IHttpClientFactory。这包罗直接利用IHttpClientFactory、利用定名client和范例client。
根基的或一般的利用模式,即直接利用IHttpClientFactory—在前面的小节中已经接头过了。请参考“注册一个IHttpClientFactory实例”一节,该节接头了如何注册HttpClient实例。
假如你想利用差异设置的HttpClient实例,以下是一个不错的选择。下面的代码片断说明白如何建设。
services.AddHttpClient("github", c => { c.BaseAddress = new Uri("https://api.github.com/"); c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); c.DefaultRequestHeaders.Add("User-Agent", "This is a test user agent"); });
第二种要领是利用包装了HttpClient实例的自界说类,该自界说类封装了通过HTTP协议挪用所有终结点的逻辑。下面的代码片断说明白如何界说自界说HttpClient类。
public class ProductService : IProductService { private IHttpClientFactory _httpClientFactory; private readonly HttpClient _httpClient; private readonly string _baseUrl = "http://localhost:1810/"; public ProductService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<Catalog> GetAllProducts() { _httpClient = _httpClientFactory.CreateClient(); _httpClient.BaseAddress = new Uri(_baseUrl); var uri = "/api/products"; var result = await _httpClient.GetStringAsync(uri); return JsonConvert.DeserializeObject<Product>(result); } }
通过以下代码注册自界说的client:
services.AddHttpClient<IProductService, ProductService>();
将MessageHandler添加到定名管道中MessageHandler是扩展自HttpMessageHandler类,它可以接管HTTP请求并返回HTTP响应。假如你想构建本身的MessageHandler,你应该建设一个担任DelegatingHandler的类。
你可以将HttpMessageHandler添加到请求处理惩罚管道中。可以在Startup类的ConfigureServices要领中利用以下代码将HttpMessageHandler添加到管道中。
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("github", c => { c.BaseAddress = new Uri("https://api.github.com/"); }) .AddHttpMessageHandler<DemoHandler>(); services.AddTransient<DemoHandler>(); }
IHttpClientFactory是一个自.net Core 2.1以来就可用的工场类。假如你利用IHttpClientFactory来建设HttpClient实例,那么底层HttpClientMessagehandler实例的池化和生命周期将自动打点。IHttpClientFactory还认真处理惩罚一些常见问题,好比日志记录。
到此这篇关于详解如安在ASP.NET Core中利用IHttpClientFactory的文章就先容到这了,更多相关ASP.NET Core利用IHttpClientFactory内容请搜索剧本之家以前的文章或继承欣赏下面的相关文章但愿各人今后多多支持剧本之家!
您大概感乐趣的文章: