這篇文章主要介紹“.NET CORE HttpClient是怎么用的”,在日常操作中,相信很多人在.NET CORE HttpClient是怎么用的問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”.NET CORE HttpClient是怎么用的”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比邢臺網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式邢臺網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋邢臺地區(qū)。費(fèi)用合理售后完善,10多年實(shí)體公司更值得信賴。前言
自從HttpClient誕生依賴,它的使用方式一直備受爭議,framework版本時代產(chǎn)生過相當(dāng)多經(jīng)典的錯誤使用案例,包括Tcp鏈接耗盡、DNS更改無感知等問題。有興趣的同學(xué)自行查找研究。在.NETCORE版本中,提供了IHttpClientFactory用來創(chuàng)建HttpClient以解決之前的種種問題。那么我們一起看一下它的用法。
使用方式
基本用法。 直接注入IHttpClientFactory
命名客戶端。注入IHttpClientFactory并帶有名稱,適用于需要特定的客戶端配置
類型化客戶端。類似于命名客戶端,但不需要名稱作為標(biāo)識,直接和某個服務(wù)類綁定在一起。注:這種方式經(jīng)測試貌似不適用控制臺程序。
生成客戶端。這種方式相當(dāng)于在客戶端生成對應(yīng)的代理服務(wù),一般特定的需要才需要這種方式。需要結(jié)合第三方庫如 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
通過IHttpClientFactory創(chuàng)建的客戶端默認(rèn)記錄所有請求的日志消息,并每個客戶端的日志類別會包含客戶端名稱,例如,名為 MyNamedClient 的客戶端記錄類別為“System.Net.Http.HttpClient.MyNamedClient.LogicalHandler”的消息。
請求管道
同framework時代的HttpClient一樣支持管道處理。需要自定義一個派生自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的時候注入進(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都會返回一個全新的HttpClient實(shí)例。而負(fù)責(zé)http請求處理的核心HttpMessageHandler將會有工廠管理在一個池中,可以重復(fù)使用,以減少資源消耗。HttpMessageHandler默認(rèn)生成期為兩分鐘??梢栽诿總€命名客戶端上重寫默認(rèn)值:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("extendedhandlerlifetime") .SetHandlerLifetime(TimeSpan.FromMinutes(5)); }
Polly支持
Polly是一款為.NET提供恢復(fù)能力和瞬態(tài)故障處理的庫,它的各種策略應(yīng)用(重試、斷路器、超時、回退等)。IHttpClientFactory增加了對其的支持,它的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)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
文章題目:.NETCOREHttpClient是怎么用的-創(chuàng)新互聯(lián)
本文URL:http://www.rwnh.cn/article36/coispg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、網(wǎng)站策劃、網(wǎng)站營銷、用戶體驗、網(wǎng)站收錄、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容