您好,登錄后才能下訂單哦!
這篇文章主要介紹“.NET CORE HttpClient是怎么用的”,在日常操作中,相信很多人在.NET CORE HttpClient是怎么用的問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”.NET CORE HttpClient是怎么用的”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
前言
自從HttpClient誕生依賴,它的使用方式一直備受爭(zhēng)議,framework版本時(shí)代產(chǎn)生過(guò)相當(dāng)多經(jīng)典的錯(cuò)誤使用案例,包括Tcp鏈接耗盡、DNS更改無(wú)感知等問(wèn)題。有興趣的同學(xué)自行查找研究。在.NETCORE版本中,提供了IHttpClientFactory用來(lái)創(chuàng)建HttpClient以解決之前的種種問(wèn)題。那么我們一起看一下它的用法。
使用方式
基本用法。 直接注入IHttpClientFactory
命名客戶端。注入IHttpClientFactory并帶有名稱,適用于需要特定的客戶端配置
類型化客戶端。類似于命名客戶端,但不需要名稱作為標(biāo)識(shí),直接和某個(gè)服務(wù)類綁定在一起。注:這種方式經(jīng)測(cè)試貌似不適用控制臺(tái)程序。
生成客戶端。這種方式相當(dāng)于在客戶端生成對(duì)應(yīng)的代理服務(wù),一般特定的需要才需要這種方式。需要結(jié)合第三方庫(kù)如 Refit 使用。這里不具體介紹。
示例代碼
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 創(chuàng)建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
通過(guò)IHttpClientFactory創(chuàng)建的客戶端默認(rèn)記錄所有請(qǐng)求的日志消息,并每個(gè)客戶端的日志類別會(huì)包含客戶端名稱,例如,名為 MyNamedClient 的客戶端記錄類別為“System.Net.Http.HttpClient.MyNamedClient.LogicalHandler”的消息。
請(qǐng)求管道
同framework時(shí)代的HttpClient一樣支持管道處理。需要自定義一個(gè)派生自DelegatingHandler的類,并實(shí)現(xiàn)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的時(shí)候注入進(jìn)去
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每次調(diào)用CreateHttpClient都會(huì)返回一個(gè)全新的HttpClient實(shí)例。而負(fù)責(zé)http請(qǐng)求處理的核心HttpMessageHandler將會(huì)有工廠管理在一個(gè)池中,可以重復(fù)使用,以減少資源消耗。HttpMessageHandler默認(rèn)生成期為兩分鐘??梢栽诿總€(gè)命名客戶端上重寫默認(rèn)值:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("extendedhandlerlifetime") .SetHandlerLifetime(TimeSpan.FromMinutes(5)); }
Polly支持
Polly是一款為.NET提供恢復(fù)能力和瞬態(tài)故障處理的庫(kù),它的各種策略應(yīng)用(重試、斷路器、超時(shí)、回退等)。IHttpClientFactory增加了對(duì)其的支持,它的nuget包為: Microsoft.Extensions.Http.Polly。注入方式如下:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient<UnreliableEndpointCallerService>() .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600))); }
總結(jié)
到此,關(guān)于“.NET CORE HttpClient是怎么用的”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。