.net Core using IHttpClientFactory request implementation

Time:2020-3-14

Guide: This article has been added to the dawn micro service journey. Now I am trying to build a micro service architecture, and I am learning and doing projects to enter the state quickly. Of course, in the process of learning, I will share what I have learned.

1、 Why not use httpclient

1. After httpclient is used, it will not immediately close and open the network connection, which will occupy the underlying socket resource. However, when httpclient calls its own dispose method, it cannot immediately release the resource

2. If you use httpclient frequently and open the link frequently, closing the link will consume a lot.

2、 Solutions

1. We can extend the life cycle of httpclient, such as building a static object


private static HttpClient Client = new HttpClient();

2. Or use singleton mode. As for which singleton mode you use, it’s up to you. I won’t go into details here. Because it doesn’t feel very comfortable

3、 Httpclientfactory

1. Httpclientfactory introduced after. Net core version 2.1 solves all the pain points of httpclient. With httpclientfactory, we don’t need to worry about how to create and release httpclient. Through it, httpclient with specific business can be created, and it can be used with di container in a friendly way, which is more flexible.

2. Httpclient created by httpclientfactory, that is, httpclienthandler, but these httpclients are put into the “pool”. The factory will automatically determine whether to create or reuse each time it creates. (the default life cycle is 2min, which can be modified)

//Modify the default lifecycle
  services.AddHttpClient()
 .SetHandlerLifetime(TimeSpan.FromMinutes(5));

4、 Use of httpclientfactory

1、 First way of use

Register in startup.cs

//Register HTTP request service
 services.AddHttpClient();

2. Used in httphelp request helper class

/// <summary>
    ///Inject HTTP request
    /// </summary>
    private readonly IHttpClientFactory httpClientFactory;
    public HttpHelp(IHttpClientFactory _httpClientFactory)
    {
      httpClientFactory = _httpClientFactory;
    }

    // <summary>
    //Get request data
    //< para > finally submit as URL parameter < / para >
    // </summary>
    //< param name = "parameters" > parameter dictionary, can be empty < / param >
    //< param name = "requesturi" > for example / API / files / UploadFile < / param >
    // <returns></returns>
    public async Task<string> Get(Dictionary<string, string> parameters, string requestUri, string token)
    {
      //Get request object from factory
      var client = httpClientFactory.CreateClient();
      //Add request header
      if (!string.IsNullOrWhiteSpace(token))
      {
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
      }
      client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
      //Splicing address
      if (parameters != null)
      {
        var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
        requestUri = string.Concat(requestUri, '?', strParam);
      }
      client.BaseAddress = new Uri(requestUri);
      return client.GetStringAsync(requestUri).Result;
    }

3. Then we can register the relative classes in startup.cs.

2、 Use named client

1. Register in startup.cs. There can be multiple registrations. Differentiate by creating a name


services.AddHttpClient("github", c =>
{
  c.BaseAddress = new Uri("https://xxxxxxx.com/");
  // Github API versioning
  c.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
  // Github requires a user-agent
  c.DefaultRequestHeaders.Add("Authorization", "asfasfasdsgdsfsdfsdafasfas");
});

2. The way of use is the same as above as long as

/// <summary>
    ///Inject HTTP request
    /// </summary>
    private readonly IHttpClientFactory httpClientFactory;
    public HttpHelp(IHttpClientFactory _httpClientFactory)
    {
      httpClientFactory = _httpClientFactory;
    }

    // <summary>
    //Get request data
    //< para > finally submit as URL parameter < / para >
    // </summary>
    //< param name = "parameters" > parameter dictionary, can be empty < / param >
    //< param name = "requesturi" > for example / API / files / UploadFile < / param >
    // <returns></returns>
    public async Task<string> Get(Dictionary<string, string> parameters, string requestUri, string token)
    {
      //Get the request object from the factory and declare which httpclient client you want to create
      var client = httpClientFactory.CreateClient("github");
      //Add request header
      if (!string.IsNullOrWhiteSpace(token))
      {
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
      }
      client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
      //Splicing address
      if (parameters != null)
      {
        var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
        requestUri = string.Concat(requestUri, '?', strParam);
      }
      client.BaseAddress = new Uri(requestUri);
      return client.GetStringAsync(requestUri).Result;
    }

3、 Typed client

1. Create a class

public class HttpClienService
{
  public HttpClient Client { get; }
  public HttpClienService(HttpClient client)
  {
    client.BaseAddress = new Uri("https://xxxx.com/");
    // GitHub API versioning
    client.DefaultRequestHeaders.Add("Authorization",
      "xxxxxxxxxxxx");
    // GitHub requires a user-agent
    client.DefaultRequestHeaders.Add("Content-Type",
      "application/json; charset=utf-8");
    Client = client;
  }

  //Here's how to write your own methods and call them
}

2. Register in startup.cs. There can be multiple registrations.

services.AddHttpClient<classHttp>();
//After registration, use dependency injection to inject and use.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Focus on Android 11: development language

Author / product manager David winer In the previous weeksof Android series, we covered contacts and identities, privacy and security Android 11 compatibility This issue willFocus on language。 We will bring you the “weeksof Android” content one after another, and explore the key technology points of Android in depth. You will not miss any important […]