您好,登录后才能下订单哦!
小编这次要给大家分享的是如何使用.NET CORE HttpClient,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
前言
自从HttpClient诞生依赖,它的使用方式一直备受争议,framework版本时代产生过相当多经典的错误使用案例,包括Tcp链接耗尽、DNS更改无感知等问题。有兴趣的同学自行查找研究。在.NETCORE版本中,提供了IHttpClientFactory用来创建HttpClient以解决之前的种种问题。那么我们一起看一下它的用法。
使用方式
示例代码
public void ConfigureServices(IServiceCollection services) { //普通注入 serviceCollection.AddHttpClient(); //命名注入 serviceCollection.AddHttpClient(Constants.SERVICE_USERACCOUNT, (serviceProvider, c) => { var configuration = serviceProvider.GetRequiredService<IConfiguration>(); c.BaseAddress = new Uri(configuration.GetValue<string>("ServiceApiBaseAddress:UserAccountService")); }); //类型化客户端 services.AddHttpClient<TypedClientService>(); } public class AccreditationService { private IHttpClientFactory _httpClientFactory; private const string _officialAccreName = "manage/CommitAgencyOfficialOrder"; private const string _abandonAccUserName = "info/AbandonUserAccreditationInfo"; public AccreditationService(IHttpClientFactory clientFactory) { _httpClientFactory = clientFactory; } public async Task<string> CommitAgentOfficial(CommitAgencyOfficialOrderRequest request) { //使用factory 创建httpclient var httpClient = _httpClientFactory.CreateClient(Constants.SERVICE_ACCREDITATION); var response = await httpClient.PostAsJsonAsync(_officialAccreName, request); if (!response.IsSuccessStatusCode) return string.Empty; var result = await response.Content.ReadAsAsync<AccreditationApiResponse<CommitAgencyOfficialOrderResult>>(); if (result.ReturnCode != "0") return string.Empty; return result.Data.OrderNo; } }
命名化客户端方式直接注入的是HttpClient而非HttpClientFactory
public class TypedClientService { private HttpClient _httpClient; public TypedClientService(HttpClient httpClient) { _httpClient = httpClient; } }
Logging
通过IHttpClientFactory创建的客户端默认记录所有请求的日志消息,并每个客户端的日志类别会包含客户端名称,例如,名为 MyNamedClient 的客户端记录类别为“System.Net.Http.HttpClient.MyNamedClient.LogicalHandler”的消息。
请求管道
同framework时代的HttpClient一样支持管道处理。需要自定义一个派生自DelegatingHandler的类,并实现SendAsync方法。例如下面的例子
public class ValidateHeaderHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!request.Headers.Contains("X-API-KEY")) { return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent( "You must supply an API key header called X-API-KEY") }; } return await base.SendAsync(request, cancellationToken); } }
在AddHttpClient的时候注入进去
public void ConfigureServices(IServiceCollection services) { services.AddTransient<ValidateHeaderHandler>(); services.AddHttpClient("externalservice", c => { // Assume this is an "external" service which requires an API KEY c.BaseAddress = new Uri("https://localhost:5001/"); }) .AddHttpMessageHandler<ValidateHeaderHandler>(); }
原理和生存周期
IHttpClientFactory每次调用CreateHttpClient都会返回一个全新的HttpClient实例。而负责http请求处理的核心HttpMessageHandler将会有工厂管理在一个池中,可以重复使用,以减少资源消耗。HttpMessageHandler默认生成期为两分钟。可以在每个命名客户端上重写默认值:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("extendedhandlerlifetime") .SetHandlerLifetime(TimeSpan.FromMinutes(5)); }
Polly支持
Polly是一款为.NET提供恢复能力和瞬态故障处理的库,它的各种策略应用(重试、断路器、超时、回退等)。IHttpClientFactory增加了对其的支持,它的nuget包为: Microsoft.Extensions.Http.Polly。注入方式如下:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient<UnreliableEndpointCallerService>() .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600))); }
看完这篇关于如何使用.NET CORE HttpClient的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。