How to use. Net core httpclient

Time:2021-2-19

preface

Since the birth of httpclient, its usage has been controversial. In the era of framework, there have been quite a number of classic misuse cases, including TCP link exhaustion, DNS change imperceptibility and so on. Interested students to find their own research. In. Net core version, ihttpclientfactory is provided to create httpclient to solve previous problems. Let’s take a look at its usage.

Usage

  • Basic usage. Direct injection into ihttpclientfactory
  • Name the client. Injects ihttpclientfactory with a name for the specific client configuration required
  • Typed client. It’s similar to naming a client, but it doesn’t need a name as an identity. It’s directly bound to a service class. Note: it seems that this method is not suitable for console program after testing.
  • Build the client. This method is equivalent to generating the corresponding proxy service on the client, which is generally required for specific needs. It needs to be used in combination with third-party libraries such as refit. There is no specific introduction here.

Sample code

public void ConfigureServices(IServiceCollection services)
{
 //General injection
 serviceCollection.AddHttpClient();
 //Named injection
 serviceCollection.AddHttpClient(Constants.SERVICE_USERACCOUNT, (serviceProvider, c) =>
 {
  var configuration = serviceProvider.GetRequiredService<IConfiguration>();
 c.BaseAddress = new Uri(configuration.GetValue<string>("ServiceApiBaseAddress:UserAccountService"));
 });
 //Typed client
 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)
 {
    //Using factory to create 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;
 }
}

The named client directly injects httpclient instead of httpclientfactory


public class TypedClientService
{
 private HttpClient _httpClient;

 public TypedClientService(HttpClient httpClient)
 {
  _httpClient = httpClient;
 }
}

Logging

Clients created through ihttpclientfactory record all requested log messages by default, and the log category of each client will contain the client name. For example, the client record category named mynamedclient is“ System.Net.Http . HttpClient.MyNamedClient.LogicalHandler ”I’m sorry to hear from you.

Request pipeline

Like httpclient in the era of framework, it supports pipeline processing. You need to customize a class derived from delegatinghandler and implement the sendasync method. For example, the following example


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

Inject it in 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>();
}

Principle and life cycle

Each time ihttpclientfactory calls createhttpclient, it will return a new instance of httpclient. Httpmessage handler, the core of HTTP request processing, will be managed in a pool by a factory, which can be reused to reduce resource consumption. The default generation period of httpmessage handler is two minutes. You can override the default values on each named client:


public void ConfigureServices(IServiceCollection services)
{   
 services.AddHttpClient("extendedhandlerlifetime")
  .SetHandlerLifetime(TimeSpan.FromMinutes(5));
}

Polly support

Polly is a library that provides resilience and transient fault handling for. Net. It has various policy applications (retry, circuit breaker, timeout, fallback, etc.). Ihttpclientfactory adds support for it. Its nuget package is: Microsoft.Extensions.Http .Polly。 The injection method is as follows:


public void ConfigureServices(IServiceCollection services)
{   
 services.AddHttpClient<UnreliableEndpointCallerService>()
  .AddTransientHttpErrorPolicy(p => 
   p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600)));

}

For more details, please refer to: https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory

summary

Here is the article about how to use. Net core httpclient. For more information about how to use. Net core httpclient, please search previous articles of developer or continue to browse the following articles. I hope you can support developer more in the future!