最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.NET CORE HttpClient的使用方法

 更新時(shí)間:2020年07月29日 09:01:58   作者:xiaogui340  
這篇文章主要給大家介紹了關(guān)于.NET CORE HttpClient的使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用.NET CORE具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(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è)命名客戶端上重寫(xiě)默認(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)));

}

更詳細(xì)的結(jié)合使用請(qǐng)參考:https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory

總結(jié)

到此這篇關(guān)于.NET CORE HttpClient使用方法的文章就介紹到這了,更多相關(guān).NET CORE HttpClient使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

邓州市| 茶陵县| 简阳市| 绿春县| 诸暨市| 怀来县| 木里| 宁德市| 浏阳市| 明水县| 唐山市| 长春市| 观塘区| 永平县| 涟源市| 普洱| 伊吾县| 黄梅县| 桃园市| 厦门市| 林芝县| 正镶白旗| 布拖县| 西藏| 永安市| 临高县| 通化县| 乌拉特中旗| 新田县| 大埔县| 安多县| 泰顺县| 栾川县| 棋牌| 洪湖市| 惠安县| 汉沽区| 清涧县| 襄汾县| 鄂托克旗| 海淀区|