.net Core request using IHttpClientFactory

        REVIEW: This article has been added to the trip dawn of micro-services , now has his own attempt at micro-service architecture, quickly enter the state while learning by doing projects. Of course, in the process of learning put their acquired knowledge to share.

First, why do not HttpClient

        After 1.HttPClient when finished using does not close immediately open network resources will take up the underlying socket connection, but calls its own Dispose method in HttpClient, and the resources can not be released immediately

         2. If you frequently use HttpClient, frequently open the link, the close link consumption will be enormous.

Second, the solution

        1. HttpClient we can extend the life cycle, such as its built a static object

private static HttpClient Client = new HttpClient();

          2. Or use a singleton, as to which one you use single-case model on your own, and there will not be a fine. Because it feels not very comfortable

Three, HttpClientFactory

       1. After .NET Core 2.1 version introduced HttpClientFactory solve all the pain points of HttpClient. With HttpClientFactory, we do not need to be concerned about how to create HttpClient, and how to release it. It can be very friendly and DI container by using it in conjunction with a specific business can create HttpClient, and more flexible.

    2.HttpClientFactory created HttpClient, that is, HttpClientHandler, but these two HttpClient was placed in the "pool" in the factory at a time when it will automatically create the judge is new or reuse. (The default life cycle 2min, you can modify the default lifecycle)
   // modify the default lifecycle 
services.AddHttpClient () .SetHandlerLifetime (TimeSpan.FromMinutes (
5 ));

Four, HttpClientFactory use 

    A first way to use

  1. Registered in the Startup.cs
                // Register http request services 
                services.AddHttpClient ();

         2.Httphelper request using auxiliary class

///  <Summary> 
        /// injection http request
         ///  </ Summary> 
        Private  Readonly IHttpClientFactory httpClientFactory;
         public HttpHelp (IHttpClientFactory _httpClientFactory) 
        { 
            httpClientFactory = _httpClientFactory; 
        } 

        // <Summary>
         // the Get Data request
         // <para > final submission manner url parameter </ para>
         // </ Summary>
         // <param name = "parameters"> parameter dictionary, can be empty </ param>
         // <param name = "requestUri"> e.g. / api / Files / UploadFile </ param
         >//<Returns> </ Returns> 
        public  the async the Task < String > the Get (the Dictionary < String , String > Parameters, String requestUri, String token) 
        { 
            // Get request object from the plant 
            var Client = httpClientFactory.CreateClient ();
             // add request head 
            IF (! String .IsNullOrWhiteSpace (token)) 
            { 
                client.DefaultRequestHeaders.Add ( " the Authorization " , " Bearer " + token); 
            }
            client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            //拼接地址
            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 pair of opposing classes will be able to use registered in Startup.cs.

      Second, use a named client

     1. Sign in Startup.cs in this registration can be multiple . To create a distinguished 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. Use the same way and as long as the above

///  <Summary> 
        /// injection http request
         ///  </ Summary> 
        Private  Readonly IHttpClientFactory httpClientFactory;
         public HttpHelp (IHttpClientFactory _httpClientFactory) 
        { 
            httpClientFactory = _httpClientFactory; 
        } 

        // <Summary>
         // the Get Data request
         // <para > final submission manner url parameter </ para>
         // </ Summary>
         // <param name = "parameters"> parameter dictionary, can be empty </ param>
         // <param name = "requestUri"> e.g. / api / Files / UploadFile </ param
         >//<Returns> </ Returns> 
        public  the async the Task < String > the Get (the Dictionary < String , String > Parameters, String requestUri, String token) 
        { 
            // Get request object httpClient declare that creates a client from which the plant 
            var Client = httpClientFactory. CreateClient ( " GitHub " );
             // add request header 
            IF (! String .IsNullOrWhiteSpace (token)) 
            { 
                client.DefaultRequestHeaders.Add ( " the Authorization " , " Bearer" + token);
            }
            client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            //拼接地址
            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;
        }

         Third, the type of 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",
             " The Application / json; charset = UTF-8 " ); 
        Client = Client; 
    } 

// The following method is to write your own, call }

             2. Sign in Startup.cs in this registration can be multiple.

services.AddHttpClient <classHttp> (); 
then // register, way dependency injection injection, use.

Guess you like

Origin www.cnblogs.com/chenxi001/p/12203731.html