When working in applications in ASP.NET Core you might frequently need to summon the Web API action orders using HttpClient to check if the endpoints are working fine. To accomplish this_ you would typically instantiate HttpClient and use the entreaty to summon your action orders. However_ there are true downsides to using HttpClient straightly_ principally having to do with managing the lifetimes of the entreatys manually.
You can quit these downsides by using IHttpClientFactory to form your HttpClient entreatys. Introduced in .NET Core 2.1_ IHttpClientFactory prepares a mediate locate to name_ configure_ and form HttpClient entreatys and feels the pooling and lifetimes of the entreatys automatically.
IHttpClientFactory is an interface that is instrumented by the DefaultHttpClientFactory class_ which is an opinionated factory. The DefaultHttpClientFactory instruments the IHttpClientFactory and IHttpMessageHandlerFactory interfaces. IHttpClientFactory was introduced to prepare ASP.NET Core with excellent built-in support for creating_ caching_ and disposing of HttpClient entreatys.
Note that HttpClientFactory discussed in my earlier article is just a helper to form HttpClient entreatys configured with the feelrs granted. This class has the pursueing orders:
CreateDelegatingHandler[]
The overloaded Create orders of the HttpClientFactory class look like this:
open static HttpClient Createparams DelegatingHandler[] feelrs{ recur Createnew HttpClientHandler_ feelrs; }<_pre> <_aside> open static HttpClient CreateHttpMessageHandler innerHandler_ params DelegatingHandler[] feelrs{ HttpMessageHandler pipeline _ CreatePipelineinnerHandler_ feelrs; recur new HttpClientpipeline; }<_pre> Both HttpClientFactory and IHttpClientFactory were introduced to better feel the lifetime of HttpMessageHandler entreatys.
Why use IHttpClientFactory?
When you dispose of a HttpClient entreaty_ the junction remains open for up to four minutes. Further_ the number of sockets that you can open at any point in time has a limit — you cant have too many sockets open at once. So when you use too many HttpClient entreatys_ you might end up exhausting your furnish of sockets.
Heres where IHttpClientFactory comes to the rescue. You can take gain of IHttpClientFactory to form HttpClient entreatys for invoking HTTP API orders by adhering to the best practices to quit issues faced with HttpClient. The first goal of IHttpClientFactory in ASP.NET Core is to fix that HttpClient entreatys are formd using the factory while at the same time eliminating socket exhaustion.
Register an IHttpClientFactory entreaty in ASP.NET Core
You can register an entreaty of type IHttpClientFactory in the ConfigureServices order of the Startup class by calling the AddHttpClient extension order on the IServiceCollection entreaty as shown in the code snippet given under.
open void ConfigureServicesIServiceCollection services{ services.AddControllersWithViews; services.AddHttpClient; }<_pre> Inject an IHttpClientFactory entreaty to your controllers in ASP.NET Core
You can then inject an IHttpClientFactory entreaty to your controllers as shown in the code snippet given under.
open class HomeController : Controller{ special IHttpClientFactory _httpClientFactory; special readonly ILoggerlt;HomeControllergt; _logger; open HomeControllerILoggerlt;HomeControllergt; logger_ IHttpClientFactory httpClientFactory { _logger _ logger; _httpClientFactory _ httpClientFactory; } __Your action orders go here }<_pre> Call your action orders using HttpClient in ASP.NET Core
To form an HttpClient using IHttpClientFactory_ you should call the CreateClient order. Once the HttpClient entreaty is useful_ you can use the pursueing code in the Index action order of the HomeController class to summon the Get order of the ValuesController class.
open async Tasklt;IActionResultgt; Index{ HttpClient httpClient _ _httpClientFactory.CreateClient; httpClient.BaseAddress _ new Uri"http:__localhost:1810_"; var response _ await httpClient.GetAsync"_api_values"; string str _ await response.Content.ReadAsStringAsync; Listlt;stringgt; data _ JsonSerializer.Deserializelt;Listlt;stringgt;gt;str; recur Viewdata; }<_pre> Use IHttpClientFactory to form and feel HttpClient entreatys in ASP.NET Core
There are separate ways you can use IHttpClientFactory in your application. These include using IHttpClientFactory straightly_ using named clients_ and using typed clients.
The basic or general usage model—i.e._ using IHttpClientFactory straightly—has already been discussed in the precedent sections. Refer to the section “Register an IHttpClientFactory entreaty” that discusses how you can register an HttpClient entreaty.
Using named clients
If you would like to use HttpClient entreatys with different configurations_ named clients is a good choice. The pursueing code snippet elucidates how you can form a named client.
services.AddHttpClient"github"_ c _gt;{ c.BaseAddress _ new Uri"https:__api.github.com_"; c.DefaultRequestHeaders.Add"Accept"_ "application_vnd.github.v3+json"; c.DefaultRequestHeaders.Add"User-Agent"_ "This is a test user agent"; };<_pre> Using typed clients
A typed client is defined using a manner class that wraps an HttpClient entreaty_ encapsulating the logic for calls to all of the endpoints over the HTTP protocol. The pursueing code snippet elucidates how a manner HttpClient class can be defined.
open class ProductService : IProductService{ special IHttpClientFactory _httpClientFactory; special readonly HttpClient _httpClient; special readonly string _baseUrl _ "http:__localhost:1810_"; open ProductServiceHttpClient httpClient { _httpClient _ httpClient; } open async Tasklt;Cataloggt; GetAllProducts { _httpClient _ _httpClientFactory.CreateClient; _httpClient.BaseAddress _ new Uri_baseUrl; var uri _ "_api_products"; var result _ await _httpClient.GetStringAsyncuri; recur JsonConvert.DeserializeObjectlt;Productgt;result; } }<_pre> The pursueing code snippet shows how you can register your manner typed HttpClient.
services.AddHttpClientlt;IProductService_ ProductServicegt;;<_pre>Add MessageHandlers to the pipeline in ASP.NET Core
A Message feelr is a class that extends the HttpMessageHandler class_ accepts an HTTP request_ and recurs an HTTP response. If you would like to build your own communication feelr_ you should form a class that extends the DelegatingHandler class.
You can add HttpMessageHandlers to the request processing pipeline. If youre using a named client_ you can use the pursueing code in the ConfigureServices order of the Startup class to add communication feelrs to the pipeline.
open void ConfigureServicesIServiceCollection services{ services.AddHttpClient"github"_ c _gt; { c.BaseAddress _ new Uri"https:__api.github.com_"; } .AddHttpMessageHandlerlt;DemoHandlergt;; services.AddTransientlt;DemoHandlergt;; }<_pre> IHttpClientFactory is an opinionated factory that has been useful since .NET Core 2.1. If you use IHttpClientFactory to form your HttpClient entreatys_ then the pooling and lifetime of the underlying HttpClientMessagefeelr entreatys are feeld for you automatically. IHttpClientFactory also takes care of ordinary concerns such as logging.
How to do more in ASP.NET Core:
- How to use the ProblemDetails middleware in ASP.NET Core<_li>
- How to form way constraints in ASP.NET Core<_li>
- How to feel user secrets in ASP.NET Core<_li>
- How to build gRPC applications in ASP.NET Core<_li>
- How to redirect a request in ASP.NET Core<_li>
- How to use attribute routing in ASP.NET Core<_li>
- How to pass parameters to action orders in ASP.NET Core MVC<_li>
- How to use API Analyzers in ASP.NET Core<_li>
- How to use way data tokens in ASP.NET Core<_li>
- How to use API versioning in ASP.NET Core<_li>
- How to use Data Transfer Objects in ASP.NET Core 3.1<_li>
- How to feel 404 errors in ASP.NET Core MVC<_li>
- How to use dependency injection in action filters in ASP.NET Core 3.1<_li>
- How to use the discretions model in ASP.NET Core<_li>
- How to use endpoint routing in ASP.NET Core 3.0 MVC<_li>
- How to ship data to Excel in ASP.NET Core 3.0<_li>
- How to use LoggerMessage in ASP.NET Core 3.0<_li>
- How to send emails in ASP.NET Core<_li>
- How to log data to SQL Server in ASP.NET Core<_li>
- How to schedule jobs using Quartz.NET in ASP.NET Core<_li>
- How to recur data from ASP.NET Core Web API<_li>
- How to format response data in ASP.NET Core<_li>
- How to use an ASP.NET Core Web API using RestSharp<_li>
- How to accomplish async operations using Dapper<_li>
- How to use component flags in ASP.NET Core<_li>
- How to use the FromServices attribute in ASP.NET Core<_li>
- How to work with cookies in ASP.NET Core<_li>
- How to work with static files in ASP.NET Core<_li>
- How to use URL Rewriting Middleware in ASP.NET Core<_li>
- How to instrument rate limiting in ASP.NET Core<_li>
- How to use Azure Application Insights in ASP.NET Core<_li>
- Using advanced NLog components in ASP.NET Core<_li>
- How to feel errors in ASP.NET Web API<_li>
- How to instrument global qualification handling in ASP.NET Core MVC<_li>
- How to feel null values in ASP.NET Core MVC<_li>
- Advanced versioning in ASP.NET Core Web API<_li>
- How to work with worker services in ASP.NET Core<_li>
- How to use the Data Protection API in ASP.NET Core<_li>
- How to use conditional middleware in ASP.NET Core<_li>
- How to work with session state in ASP.NET Core<_li>
- How to write efficient controllers in ASP.NET Core<_li> <_ul>