溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在.Net中使用HTTP請(qǐng)求IHttpClientFactory

發(fā)布時(shí)間:2021-03-08 14:21:46 來源:億速云 閱讀:316 作者:Leah 欄目:開發(fā)技術(shù)

如何在.Net中使用HTTP請(qǐng)求IHttpClientFactory?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

使用方式

IHttpClientFactory有四種模式:

  • 基本用法

  • 命名客戶端

  • 類型化客戶端

  • 生成的客戶端

基本用法

在 Startup.ConfigureServices 方法中,通過在 IServiceCollection 上調(diào)用 AddHttpClient 擴(kuò)展方法可以注冊 IHttpClientFactory

services.AddHttpClient();

注冊之后可以像依賴注入DI似得在類中通過構(gòu)造函數(shù)注入形式使用,偽代碼:

class A
{
 private readonly IHttpClientFactory _clientFactory;
 public A(IHttpClientFactory clientFactory)
 {
  _clientFactory = clientFactory;
 }
 
 Public void Use()
 {
   var request=new HttpRequestMessage(HttpMethod.Get,"www.baidu.com") ;
   var client = _clientFactory.CreateClient();
   var response = await client.SendAsync(request); 
   if (response.IsSuccessStatusCode)
   {
   Branches = await response.Content.ReadAsAsync<IEnumerable<GitHubBranch>>();
   }
  else
  {
   GetBranchesError = true;
   Branches = Array.Empty<GitHubBranch>();
  }  
 }
}

命名客戶端

也是在基本用法的基礎(chǔ)上增加配置參數(shù):例如增加一個(gè)baidu下的客戶端:

services.AddHttpClient("baidu",c=>
{
 c.BaseAddress = new Uri("https://api.baidu.com/");
 //其他一些參數(shù)
});

然后在使用的時(shí)候只是需要傳遞客戶端名稱就自動(dòng)使用baidu這個(gè)地址的基礎(chǔ)地址配置:

 var client = _clientFactory.CreateClient("baidu");

類型化客戶端

說的明白一點(diǎn)就是在使用類的構(gòu)造函數(shù)中可以直接接受HttpClient 類型,不用在使用IHttpClientFactory 接口的CreateClient方法創(chuàng)建,但是首要條件就是要先創(chuàng)建注入類型,然后在ConfigureServices 方法同時(shí)注入:

services.AddHttpClient<classHttp>();

注入類型:

public class classHttp
{
   public HttpClient Client { get; }
   public GitHubService(HttpClient client)
   {
      client.BaseAddress = new Uri("https://api.baidu.com/");
      //同ConfigureServices 中一樣設(shè)置一些其他參數(shù)
      Client = client;
   }
}

生成的客戶端

這個(gè)我個(gè)人理解為就是配置使用第三方庫,然后可以注入接口類型,接口中可以寫一些方法接口。然后通過接口類直接調(diào)用接口。

個(gè)人理解:就是類似于一個(gè)接口映射,地址映射似得。通過結(jié)合第三方庫(官方推薦Refit)實(shí)現(xiàn)請(qǐng)求一個(gè)地址別名的方式,別名就是指定義的接口。然后別名通過增加特性Get(“路徑”)或者post("路徑)的形式重新指向真實(shí)的請(qǐng)求接口地址。通過請(qǐng)求這個(gè)本地接口方法實(shí)現(xiàn)轉(zhuǎn)化請(qǐng)求的真實(shí)地址。

舉例定義接口:

public interface IHelloClient
{
  [Get("/MyInterFace")]
  Task<Reply> GetMessageAsync();
}

配置Refit插件:

也是和正常配置類似,在后面增加接口的服務(wù)注入。

public void ConfigureServices(IServiceCollection services)
{
  services.AddHttpClient("hello", c =>
  {
    c.BaseAddress = new Uri("http://localhost:5000");
  })
  .AddTypedClient(c => Refit.RestService.For<IHelloClient>(c));

  services.AddMvc();
}

然后再說接口上面的Get("/MyInterFace")方法;這個(gè)我們就不做另一個(gè)項(xiàng)目就在當(dāng)前項(xiàng)目下,所以可以直接就在api項(xiàng)目下創(chuàng)建一個(gè)名為MyInterFace的方法。

[ApiController]
public class TestController : ControllerBase
{
   [HttpGet("/")]
  public async Task<sting> MyInterFace()
  {
    return "ceshi";
  }
}

然后就可以使用接口了:

[ApiController]
public class ValuesController : ControllerBase
{
  private readonly IHelloClient _client;

  public ValuesController(IHelloClient client)
  {
    _client = client;
  }

  [HttpGet("/")]
  public async Task<ActionResult<Reply>> Index()
  {
    return await _client.GetMessageAsync();
  }
}

在這了的_client.GetMessageAsync()方法就是調(diào)用了接口方法,看著是調(diào)用了GetMessageAsync方法其實(shí)是做了映射,映射地址就是上面特性寫的MyInterFace方法。通過斷點(diǎn)也可以驗(yàn)證此結(jié)論。然后不同項(xiàng)目下也是同一個(gè)意思,假如我們請(qǐng)求百度的地址:www.baidu.com/api/b這個(gè)接口

我們在配置出把請(qǐng)求地址http://localhost:5000改為www.baidu.com/api,然后再把GetMessageAsync方法上面的MyInterFace改為b即可。

出站請(qǐng)求中間件

個(gè)人理解為請(qǐng)求返回前處理程序,就是繼承 DelegatingHandler派生類重寫SendAsync 方法。在將請(qǐng)求傳遞至管道中的下一個(gè)處理程序之前執(zhí)行代碼:

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);
  }
}

然后在ConfigureServices中:

services.AddTransient<ValidateHeaderHandler>();//注冊處理程序
services.AddHttpClient("externalservice", c =>
{
  // Assume this is an "external" service which requires an API KEY
  c.BaseAddress = new Uri("https://localhost:5000/");
})
.AddHttpMessageHandler<ValidateHeaderHandler>();/注入到http請(qǐng)求管道

可以同時(shí)注冊多個(gè)處理程序。

HttpClient和生存周期

每次對(duì) IHttpClientFactory 調(diào)用 CreateClient 都會(huì)返回一個(gè)新 HttpClient 實(shí)例。 每個(gè)命名的客戶端都具有一個(gè) HttpMessageHandler。 工廠管理 HttpMessageHandler 實(shí)例的生存期。

 HttpClient實(shí)例不是與HttpMessageHandler一起銷毀的,HttpMessageHandler在池中生存,如果生命周期未到不會(huì)被銷毀,會(huì)被新的HttpClient 實(shí)例使用。

處理程序的默認(rèn)生存周期是2分鐘,可以通過配置修改:

services.AddHttpClient("extendedhandlerlifetime")
  .SetHandlerLifetime(TimeSpan.FromMinutes(5));

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI