您好,登錄后才能下訂單哦!
小編這次要給大家分享的是如何使用.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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。