<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>httpclientfactory without dependency injection - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/tag/httpclientfactory-without-dependency-injection/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Mon, 15 Apr 2024 02:21:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>httpclientfactory without dependency injection - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to use HttpClient C#- Guidelines and Best Practices</title>
		<link>https://thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/</link>
					<comments>https://thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 01 Dec 2022 21:21:00 +0000</pubDate>
				<category><![CDATA[Tips and Guidelines]]></category>
		<category><![CDATA[asp net httpclient best practices]]></category>
		<category><![CDATA[Connectionleasetimeout]]></category>
		<category><![CDATA[HttpClient ASp.NET Core 3.1]]></category>
		<category><![CDATA[httpclient best practices c#]]></category>
		<category><![CDATA[httpclient c# httpclient multiple requests c# httpclient concurrent requests httpclient reuse connection httpclient cache c#]]></category>
		<category><![CDATA[httpclient guidelines]]></category>
		<category><![CDATA[httpclient keep-alive c#]]></category>
		<category><![CDATA[httpclient performance optimization c#]]></category>
		<category><![CDATA[httpclient reuse connection]]></category>
		<category><![CDATA[httpclient socket exhaustion]]></category>
		<category><![CDATA[httpclient thread safe]]></category>
		<category><![CDATA[httpclient time_wait]]></category>
		<category><![CDATA[HttpClient usage AntiPattern]]></category>
		<category><![CDATA[Httpclientfactory]]></category>
		<category><![CDATA[httpclientfactory .net 6]]></category>
		<category><![CDATA[httpclientfactory vs httpclient]]></category>
		<category><![CDATA[httpclientfactory without dependency injection]]></category>
		<category><![CDATA[ihttpclientfactory]]></category>
		<category><![CDATA[Using HTTPClient in a better way]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=8083</guid>

					<description><![CDATA[<p>HttpClient C#- Guidelines and Best Practices In today&#8217;s article, we will discuss HttpClient C# Guidelines and Best Practices that developers can follow for developing HTTP-based APIs or microservices. We will go through various aspects of how to use/create/instantiate HttpClient C# instances in the .NET /.NET Core ecosystem. I did touch upon this topic in my [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/">How to use HttpClient C#- Guidelines and Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">HttpClient C#- Guidelines and Best Practices</h1>



<figure class="is-resized wp-block-image size-large"><a href="https://www.thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns" target="_blank" rel="noopener"><img fetchpriority="high" decoding="async" width="1024" height="512" src="https://www.thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1-1024x512.jpg" alt="HTTPClient C# Guidelines and Best Practices " class="wp-image-8301" srcset="https://thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1-1024x512.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1-300x150.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1-768x384.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1-1536x768.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1-785x393.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/02/How-to-use-HTTPClient-Best-Practices-1.jpg 1830w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="">In today&#8217;s article, we will discuss <strong><em>HttpClient </em></strong>C# Guidelines and Best Practices that developers can follow for developing HTTP-based APIs or microservices.</p>



<p class=""></p>



<p class="">We will go through various aspects of how to use/create/instantiate <strong><em>HttpClient </em></strong>C# instances in the <strong>.NET /.NET Core</strong> ecosystem.</p>



<p class=""></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-what-is-httpclient">What is HttpClient</a></li><li><a href="#aioseo-example-1---antipattern">HTTPClient Antipattern 1 &#8211; use of new HttpClient()</a></li><li><a href="#aioseo-example-2---antipattern">HttpClient AntiPattern 2 &#8211; use of Using statement</a></li><li><a href="#aioseo-why-anti-pattern">Why Anti-pattern?</a></li><li><a href="#aioseo-resource-exhaustion-and-stale-dns-problem">HttpClient &#8211; Resource Exhaustion and Stale DNS Problem</a></li><li><a href="#aioseo-resolutions">Resolutions for HttpClient AntiPatterns</a><ul><li><a href="#aioseo-example---resolution-2">Resolution 1 &#8211; Use HttpClientFactory</a></li><li><a href="#aioseo-basic-or-named-httpclient-object">Basic or Named HttpClient object</a></li><li><a href="#aioseo-typed-httpclient-objects">Typed HttpClient objects</a></li><li><a href="#aioseo-example---resolution-1">Resolution 2 &#8211; Use Static Instance of HttpClient</a></li><li><a href="#aioseo-additional-guidelines-for-dns-update-scenarios">Use PooledConnectionLifetime &#8211; DNS update scenarios,</a></li></ul></li><li><a href="#aioseo-other-resolution-and-best-practices">Other Resolution and Best Practices</a><ul><li><a href="#aioseo-set-timeout-on-httpclient-instance">Set Timeout on HttpClient Instance</a></li><li><a href="#aioseo-use-await-with-async-methods">Use await with async Methods</a></li><li><a href="#aioseo-configuring-httpclient-correctly">Configuring HTTPClient correctly</a></li><li><a href="#aioseo-using-httpclienthandler-for-customize-behaviour">Using HttpClientHandler for customizing behavior</a></li><li><a href="#aioseo-handling-exceptions-and-errors">Handling exceptions and errors</a></li><li><a href="#aioseo-implementing-retries-and-exponential-backoff">Implementing Resiliency &#8211; Retries and exponential backoff</a></li><li><a href="#aioseo-httpclient-security-considerations">HttpClient Security considerations</a></li></ul></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p class=""></p>



<p class="">I did touch upon this topic in my last article on the <strong><a aria-label="Using HTTPClientFactory in ASP.NET Core Application (opens in a new tab)" href="https://www.thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener">Using HTTPClientFactory in ASP.NET Core Application</a> </strong>already, however, today&#8217;s article is more on the guidelines and best practices while using HTTPClient instances to access resources over the network.</p>



<p class=""></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-httpclient"><h3 class="aioseo-faq-block-question">What is HttpClient </h3><div class="aioseo-faq-block-answer">
<p class=""><strong><em>HttpClient</em></strong> is a very important class in the .NET/.NET Core ecosystem. It provides you the ability to send HTTP requests and receive HTTP responses from a resource identified by a URI.</p>



<ul class="wp-block-list">
<li class="">You can use HttpClient to submit various HTTP requests, including GET, POST, PUT, DELETE, etc., and receive server responses. </li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">Because it allows asynchronous operations, programs can efficiently make non-blocking HTTP calls. </li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">It can handle JSON, XML, and other different content types.</li>
</ul>



<p class=""></p>
</div></div>



<p class="">Developers may easily use HTTPClient to handle HTTP headers and status codes, download/upload files, use web services, and consume APIs.</p>



<p class=""></p>



<p class="">HttpClient is designed as a shared instance that is also thread-safe if used properly.</p>



<p class=""></p>



<p class="">The HttpClient class is designed as a broker that clients can use to access the resource over the network.</p>



<p class=""></p>



<p class="">In the <strong>host-based application </strong>under heavy load communication, there could be multiple instances of <em>HTTPClient </em>getting created. </p>



<p class=""></p>



<p class="">Over the years it has experienced a few common issues like resource exhaustion caused by multiple invocations of the HTTP request object and then recently discovered issues with .NET Core like <strong><em>Stale DNS</em></strong>, etc.</p>



<p class=""></p>



<p class="">Let&#8217;s see, how <strong><em>HttpClient </em></strong>is currently being used in applications and issues related to that with some real-life examples. </p>



<p class=""></p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-example-1---antipattern">HTTPClient AntiPattern 1 &#8211; use of new HttpClient()</h2>



<p class=""></p>



<p class="">You instantiate the <strong>HttpClient </strong>object using a <strong><em>new </em></strong>operator for every request.</p>



<p class=""></p>



<p class="">Example: </p>



<p class=""></p>



<pre class="wp-block-preformatted">HttpClient httpClient = new HttpClient();</pre>



<p class=""></p>



<p class="">OR </p>



<p class=""></p>



<p class="">Using Handler</p>



<p class=""></p>



<figure class="is-resized wp-block-image size-large"><img decoding="async" width="1024" height="162" src="https://www.thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices-1024x162.jpg" alt="httpclient best practices c#" class="wp-image-8183" srcset="https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices-1024x162.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices-300x48.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices-768x122.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices-1536x244.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices-785x124.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-Best-Practices.jpg 1810w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [4]; title: ; notranslate">
       
            var httpClientHandler = new HttpClientHandler()
            {
                Credentials = new NetworkCredential(config.User, config.Pwd),
            };

            HttpClient httpClient = new HttpClient(httpClientHandler);

            HttpResponseMessage response = await httpClient.GetAsync(config.Url).Result;
..
..
</pre></div>


<p class=""></p>



<p class=""></p>



<p class="">In the above example, the <em><strong>HttpClient object is created for each request</strong></em> using a <em><strong>new </strong></em>operator. </p>



<p class=""></p>



<p class="">Here in the above example, the developer&#8217;s intention looks to be creating a<strong> long-lived</strong> instance that will be disposed of/garbage collected depending on the implementation. </p>



<p class=""></p>



<p class=""><strong>Note</strong>&#8211; If the instances are injected through <em><strong>IOC </strong></em>container pipelines then only it will be <strong>disposed </strong>of by the framework as default behavior or else it becomes the creator&#8217;s responsibility to manage the objects&#8217; lifetime.</p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-example-2---antipattern">HttpClient AntiPattern 2 &#8211; use of Using statement</h2>



<p class=""></p>



<p class="">In this anti-pattern example, the developer instantiates the HttpClient object <strong><em>using </em></strong>block,</p>



<p class=""></p>



<p class="">Other examples without using any handler,</p>



<p class=""></p>



<figure class="is-resized wp-block-image size-large"><img decoding="async" width="1024" height="233" src="https://www.thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1-1024x233.jpg" alt="httpclient best practices c#" class="wp-image-8192" srcset="https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1-1024x233.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1-300x68.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1-768x175.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1-1536x350.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1-785x179.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/02/using-HTTPClient-anti-patterns-1.jpg 1810w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>



<p class=""><strong>Example</strong>:  With C# <em><strong>HttpClientHandler</strong></em> </p>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
          var httpClientHandler = new HttpClientHandler()
            {
               Credentials = new NetworkCredential(config.User, config.Pwd),
            };

            HttpResponseMessage response;
            using (HttpClient httpClient = new HttpClient(httpClientHandler))
            {
                response = await httpClient.GetAsync(config.Url);
            }

  
        
</pre></div>


<p class=""></p>



<p class="">Similar to above <strong><em>example 1</em></strong>, In the above example, the HttpClient object is being created for each request. </p>



<p class=""></p>



<p class="">Here in the above example, the developer is aware that the <strong><em>HttpClient </em></strong>object is an unmanaged resource and implements IDisposable. </p>



<p class=""></p>



<p class="">Here instance gets created and called within the &#8216;<strong><em>using</em></strong>&#8216; block assuming this will be disposed of<em><strong>/garbage</strong></em> collected immediately but in reality, there is no guarantee that such resources will get disposed of at a given time. </p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-why-anti-pattern">Why Anti-pattern?</h2>



<p class=""></p>



<p class="">Using <strong><em>HTTPClient </em></strong>in the above-mentioned manner is considered to be an anti-pattern due to common problems like Resource Exhaustion and Stale DNS Problems as discussed below,</p>



<p class=""></p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-resource-exhaustion-and-stale-dns-problem">HttpClient &#8211; Resource Exhaustion and Stale DNS Problem</h2>



<p class=""></p>



<p class="">In both, of the above&nbsp;<strong>Example1&nbsp;</strong>and&nbsp;<strong>Example2&nbsp;</strong>below are the consideration and issues associated.</p>



<p class=""></p>



<ul class="wp-block-list">
<li class="">Each new&nbsp;<strong>HTTPClient&nbsp;</strong>object creates a new socket instance.</li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">Instantiating HTTPClient objects for each request might exhaust the number of sockets available<strong>&nbsp;</strong>under heavy loads.</li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">HTTPClient object doesn’t release the sockets immediately even if it is called using the “using” (<strong><em>IDisposable</em></strong>) block.</li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">This may lead to&nbsp;<strong>SocketExceptions</strong>.</li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">Singleton or Static HTTPClient objects as specified above should help to resolve most issues.</li>
</ul>



<p class=""></p>



<ul class="wp-block-list">
<li class="">In .NET Core, it was found that Singleton or Static HTTPClient object doesn’t respect the DNS update or change in the .NET core resulting in a&nbsp;<strong>Stale DNS problem</strong></li>
</ul>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-resolutions">Resolutions for HttpClient AntiPatterns</h2>



<p class=""></p>



<p class="">As per <strong><em>Microsoft </em></strong>guidelines,</p>



<p class=""></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class=""><strong>HttpClient</strong>&nbsp;is intended to be instantiated once and re-used throughout the request flow of an application.</p>



<p class="">Especially in server applications, creating a new&nbsp;<strong>HttpClient</strong>&nbsp;instance for every request will exhaust the number of sockets available under heavy loads.</p>



<p class="">This will result in&nbsp;<strong>SocketException</strong>&nbsp;errors.</p>
</blockquote>



<p class=""></p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-example---resolution-2">Resolution 1 &#8211; Use HttpClientFactory</h3>



<p class=""></p>



<p class="">Let&#8217;s create a HttpClient instance using <strong>HttpClientFactory</strong>.(Available only in .NET Core 2.1 and above)</p>



<p class=""></p>



<p class="">Using <strong>HTTPClientFactory </strong>resolves the Resource exhaustion problems by pooling HTTPMessageHandler.</p>



<p class=""></p>



<p class="">It also solves Stale <strong><em>DNS </em></strong>problems by cycling HTTPMessageHandler instances at regular intervals. </p>



<p class=""></p>



<p class="">Each instance of  <code>HttpClient</code> object created from <code>IHttpClientFactory</code>, uses an <code>HttpMessageHandler</code> that&#8217;s pooled and reused to reduce resource consumption. </p>



<p class=""></p>



<p class="">This also depends upon <code>HttpMessageHandler</code> objects lifetime which has a lifetime of two minutes typically by default.</p>



<p class=""></p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-basic-or-named-httpclient-object">Basic or Named HttpClient object </h3>



<p class=""></p>



<figure class="is-resized wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="674" src="https://www.thecodebuzz.com/wp-content/uploads/2020/02/HttpClientFactory-in-ASP.NET-Core-Best-Practices-and-Antipatterns-1024x674.jpg" alt="HTTPClient C# Best Practices and Anti-Patterns" class="wp-image-8188" srcset="https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClientFactory-in-ASP.NET-Core-Best-Practices-and-Antipatterns-1024x674.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClientFactory-in-ASP.NET-Core-Best-Practices-and-Antipatterns-300x198.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClientFactory-in-ASP.NET-Core-Best-Practices-and-Antipatterns-768x506.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClientFactory-in-ASP.NET-Core-Best-Practices-and-Antipatterns-785x517.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClientFactory-in-ASP.NET-Core-Best-Practices-and-Antipatterns.jpg 1403w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>



<p class=""></p>



<p class="">For more details see here:&nbsp;<a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Named HTTP Client using HTTPClientFactory</em></strong></a></p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-typed-httpclient-objects">Typed HttpClient objects</h3>



<p class=""></p>



<figure class="is-resized wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="577" src="https://www.thecodebuzz.com/wp-content/uploads/2020/02/HttpClient-in-ASP.NET-Core-Best-Practices-and-Antipatterns-typed-httpclient-1024x577.jpg" alt=".net 6 httpclient best practices" class="wp-image-8190" srcset="https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClient-in-ASP.NET-Core-Best-Practices-and-Antipatterns-typed-httpclient-1024x577.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClient-in-ASP.NET-Core-Best-Practices-and-Antipatterns-typed-httpclient-300x169.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClient-in-ASP.NET-Core-Best-Practices-and-Antipatterns-typed-httpclient-768x433.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClient-in-ASP.NET-Core-Best-Practices-and-Antipatterns-typed-httpclient-785x443.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/02/HttpClient-in-ASP.NET-Core-Best-Practices-and-Antipatterns-typed-httpclient.jpg 1403w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>



<p class="">For more details see here:&nbsp;<a href="https://www.thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Typed HTTP Client using HTTPClientFactory</em></strong></a></p>



<p class=""></p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-example---resolution-1">Resolution 2 &#8211; Use Static Instance of HttpClient</h3>



<p class=""></p>



<p class="">It&#8217;s recommended to create a single static HttpClient instance and use the same shared instance for all requests. </p>



<p class=""></p>



<p class="">This approach is more useful and convenient in case you have a no-host application like a batch process or console application.</p>



<p class=""></p>



<p class="">Also, for applications where dependency injection is a bit difficult to manage, this approach is a possible option. </p>



<p class=""></p>



<p class="">HttpClient is designed to be thread-safe and intended to be shared.</p>



<p class=""></p>



<p class="">If you have a console or <a href="https://www.thecodebuzz.com/file-logging-in-windows-form-application-using-serilog/">form application</a> where you need to perform repetitive HTTP connection, this approach is preferable. </p>



<p class=""></p>



<p class="">The below example shows a static instance created in the controller but the same if you have layered architecture, same can be used in the controller/API or business or data access layer as needed.</p>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [6]; title: ; notranslate">
    &#x5B;Route(&quot;api/&#x5B;controller]&quot;)]
    &#x5B;ApiController]
    public class PaymentController : ControllerBase
    {

        static readonly HttpClient client = new HttpClient();
        
        &#x5B;HttpGet]
        public  async Task&lt;IActionResult&gt; Get()
        {
            HttpClientHandler httpClientHandler = new HttpClientHandler()
            {
                Credentials = new NetworkCredential(&quot;username&quot;, &quot;****&quot;),
            };

            var response = await client.GetAsync(&quot;https://www.thecodebuzz.com/api/&quot;);
            return Ok(response.Content.ReadAsStringAsync().Result);
        }
</pre></div>


<p class=""></p>



<p class=""></p>



<figure class="is-resized wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="301" src="https://www.thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices-1024x301.jpg" alt=".net framework httpclient best practices" class="wp-image-8187" srcset="https://thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices-1024x301.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices-300x88.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices-768x226.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices-1536x452.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices-785x231.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/02/HTTPClient-in-.NET-Core-Best-Practices.jpg 1571w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>



<p class="">Additionally, you can use <strong>Constructor </strong>to initialize the HttpClient Instance.</p>



<p class=""></p>



<p class="">Below is just an example to demonstrate the use. However please use layered architecture and inject services per need.</p>



<p class=""></p>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
public class PaymentController : ControllerBase
    {
        private static  HttpClient _client;
        public PaymentController() =&gt; _client = new HttpClient();
..
}
</pre></div>


<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-additional-guidelines-for-dns-update-scenarios">Use PooledConnectionLifetime &#8211; DNS update scenarios,</h3>



<p class=""></p>



<p class="">Additionally, it&#8217;s recommended to use the <strong>PooledConnectionLifetime </strong>settings if DNS entries change regularly,</p>



<p class=""></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [9]; title: ; notranslate">
public class PaymentController : ControllerBase
{
    private static readonly HttpClient httpClient;

    static PaymentController ()
    {
        var socketsHandler = new SocketsHttpHandler
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(2)
        };

        httpClient = new HttpClient(socketsHandler);
    }
}
</pre></div>


<p class=""></p>



<p class="">The above<strong><em> use of PooledConnectionLifetime </em></strong>limits the lifetime of the connection by setting the SocketsHttpHandler.PooledConnectionLifetime property. </p>



<p class=""></p>



<p class="">In case the DNS is replaced, the connection will perform the  DNS lookup and restore the connection.</p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-other-resolution-and-best-practices"><strong>Other Resolution and Best Practices </strong></h2>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-set-timeout-on-httpclient-instance">Set Timeout on HttpClient Instance </h3>



<p class=""></p>



<p class=""> Specify a timeout value to prevent requests from hanging indefinitely. </p>



<p class="">This helps in handling scenarios where the remote server is unresponsive or experiencing delays.</p>



<p class=""></p>



<p class="">Example </p>



<p class=""></p>



<pre class="wp-block-preformatted">httpClientInstance.Timeout = TimeSpan.FromSeconds(10);</pre>



<p class=""></p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-use-await-with-async-methods">Use <em>await </em>with <em>async </em>Methods</h3>



<p class=""></p>



<p class="">When making asynchronous HTTP requests using HttpClient, utilize the <strong>async/await</strong> pattern to ensure responsiveness and avoid blocking the calling thread.</p>



<p class=""></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="245" src="https://www.thecodebuzz.com/wp-content/uploads/2023/06/Async-await-httpclient-best-practices-1024x245.jpg" alt="C# HttpClient " class="wp-image-27435" srcset="https://thecodebuzz.com/wp-content/uploads/2023/06/Async-await-httpclient-best-practices-1024x245.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/06/Async-await-httpclient-best-practices-300x72.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/06/Async-await-httpclient-best-practices-768x183.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/06/Async-await-httpclient-best-practices-785x188.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-configuring-httpclient-correctly">Configuring HTTPClient correctly</h3>



<p class=""></p>



<p class="">Configure the HttpClient instance with appropriate <em>timeouts, default headers, certificates, authentication, </em>and <em>other settings</em> like <a href="https://www.thecodebuzz.com/httpcontext-best-practices-in-net-csharp-thread-safe/" target="_blank" rel="noopener" title="HttpContext Best Practices in .NET">HttpContext </a>based on your application&#8217;s requirements. </p>



<p class=""></p>



<p class="">Use try-catch blocks or<em> async/await</em> error handling patterns when making requests with HttpClient.</p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-using-httpclienthandler-for-customize-behaviour">Using HttpClientHandler for customizing behavior</h3>



<p class=""></p>



<p class="">Consider using the HttpClientHandler class to customize the underlying HTTP behavior, such as handling certificates or enabling compression.</p>



<p class=""></p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-handling-exceptions-and-errors">Handling exceptions and errors</h3>



<p class=""></p>



<p class="">Handle exceptions such as <strong><em>HttpRequestException </em></strong>and <strong><em>TaskCanceledException </em></strong>to gracefully handle network issues, timeouts, or other errors. </p>



<p class=""></p>



<p class="">Properly logging or handling exceptions ensures the robustness and reliability of your application.</p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-implementing-retries-and-exponential-backoff">Implementing Resiliency &#8211; Retries and exponential backoff</h3>



<p class=""></p>



<p class="">When dealing with transient errors like network connectivity issues or temporary server failures, consider implementing <a href="https://www.thecodebuzz.com/httpclient-resiliency-http-polly-csharp-netcore/" target="_blank" rel="noopener" title="Polly Retry Policies and Error handling in C# .NET">Httpclient Resiliency retry </a>mechanisms with exponential backoff. </p>



<p class=""></p>



<p class="">This allows your application to automatically retry failed requests, increasing the chances of successful execution. </p>



<p class=""></p>



<h3 class="wp-block-heading" id="aioseo-httpclient-security-considerations">HttpClient Security considerations</h3>



<p class=""></p>



<p class="">When making requests to secure endpoints, ensure that you properly handle and validate <a href="https://www.thecodebuzz.com/configure-certificate-with-httpclient-authentication/" target="_blank" rel="noopener" title="How to check SSL/TLS Cipher Suites a Server Offer – Guidelines">SSL/TLS certificates</a>.</p>



<p class=""></p>



<p class="">Follow secure coding practices and validate and sanitize user inputs to prevent security vulnerabilities like injection attacks.</p>



<p class=""></p>



<p class=""></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p class=""></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary </h2>



<p class=""></p>



<p class="">In this article, we learned about <strong><em>HttpClient </em></strong>instancing usage&#8217;s best practices and guidelines. We understood that by following best practices, we can avoid common problems of <em>Resource exhaustion, stale DNS, Memory leaks, or network connectivity issues </em>while using HttpClient objects. </p>



<p class="">Using <strong><em><a href="https://www.thecodebuzz.com/top-10-benefits-of-httpclientfactory-net-csharp-api-architecture/" target="_blank" rel="noopener" title="Top 10 Benefits of HttpClientFactory in .NET">HttpClientfactory </a></em></strong>or A static shared instance is the recommended way to use the HTTPClient object in the application.</p>



<p class=""></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p><p>The post <a href="https://thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/">How to use HttpClient C#- Guidelines and Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>HttpClientFactory in ASP.NET Core with examples</title>
		<link>https://thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/</link>
					<comments>https://thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 31 Aug 2022 02:15:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[asp.net core 2.1 httpclientfactory]]></category>
		<category><![CDATA[asp.net core 3.0 httpclientfactory]]></category>
		<category><![CDATA[asp.net core 3.1 httpclientfactory]]></category>
		<category><![CDATA[autofac httpclientfactory]]></category>
		<category><![CDATA[HTTPClientFactory add authentication]]></category>
		<category><![CDATA[HTTPClientFactory add basic auth headers]]></category>
		<category><![CDATA[HTTPClientFactory add headers]]></category>
		<category><![CDATA[HTTPClientFactory add JWT bearer]]></category>
		<category><![CDATA[httpclientfactory c#]]></category>
		<category><![CDATA[HTTPClientFactory certificates]]></category>
		<category><![CDATA[httpclientfactory console app]]></category>
		<category><![CDATA[httpclientfactory createclient]]></category>
		<category><![CDATA[httpclientfactory example]]></category>
		<category><![CDATA[httpclientfactory github]]></category>
		<category><![CDATA[httpclientfactory in class library]]></category>
		<category><![CDATA[httpclientfactory net framework]]></category>
		<category><![CDATA[httpclientfactory typed client]]></category>
		<category><![CDATA[httpclientfactory without dependency injection]]></category>
		<category><![CDATA[ihttpclientfactory net core]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=7283</guid>

					<description><![CDATA[<p>HttpClientFactory in ASP.NET Core with examples In today’s post, we will see how to use HttpClientFactory in ASP.NET Core with examples in ASP.NET Core and invoke HTTP Services in .NET Core or ASP.NET Core. It’s a best practice to use the HTTPClientFactory object to create an HTTPClient object as it addresses known issues related to [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/">HttpClientFactory in ASP.NET Core with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">HttpClientFactory in ASP.NET Core with examples</h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="408" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-1024x408.jpg" alt="HTTPClient using HttpClientFactory in ASP.NET Core " class="wp-image-7544" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-1024x408.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-300x120.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-768x306.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-1536x612.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-2048x816.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2020/01/HttpClientFactory-in-ASP.NET-Core-Best-Practices-1-785x313.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In today’s post, we will see how to use HttpClientFactory in ASP.NET Core with examples <strong>in ASP.NET Core</strong> and invoke HTTP Services in .NET Core or ASP.NET Core.</p>



<p></p>



<p>It’s a best practice to use the <strong>HTTPClientFactory </strong>object to create an HTTPClient object as it addresses known issues related to HTTPClient usage in the traditional way in .NET Core.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-httpclient-in-net-core-common-issues">HTTPClient in .NET Core &#8211; Common Issues</a></li><li><a href="#aioseo-resource-exhaustion-problem">Resource Exhaustion Problem</a></li><li><a href="#aioseo-stale-dns-domain-name-system-problems">Stale DNS (Domain Name System) problems</a></li><li><a href="#aioseo-create-an-http-request-using-httpclientfactory-guidelines">Create an HTTP request using HTTPClientFactory &#8211; Guidelines</a></li><li><a href="#aioseo-basic-httpclient-request">Basic HTTPClient Request</a></li><li><a href="#aioseo-named-httpclient-request-using-httpclientfactory">HttpClientFactory  -Named HTTPClient usage with examples</a></li><li><a href="#aioseo-typed-httpclient-request-using-httpclientfactory">HttpClientFactory  -Typed HTTPClient usage with examples</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p>We shall also understand a few approaches to create <strong>HTTPClient </strong>requests using the below techniques,</p>



<p></p>



<ul class="wp-block-list"><li><strong><em>Basic HTTPClient </em></strong></li></ul>



<ul class="wp-block-list"><li><strong><em><a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener">Named HTTPClient </a></em></strong></li></ul>



<ul class="wp-block-list"><li><strong><em><a href="https://www.thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/">Typed HTTPClient</a></em></strong></li></ul>



<p></p>



<p>All the above techniques leverage the <strong>IHTTPClientFactory </strong>interface to DI (Dependency Injection) required client object.</p>



<p> </p>



<p>DI with middleware framework lets the API pipeline control the lifetime management of HTTPClient request objects instead of doing it manually.</p>



<p></p>



<p>Over the years it has been observed a few common issues like resource exhaustion caused by multiple invocations of the HTTP request object. </p>



<p></p>



<p>This was also followed by the realization that one should create Static or Singleton HTTP Client instances but which again ultimately found to be an issue in the recent .NET Core framework in the form of <strong>Stale DNS </strong>problems.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-httpclient-in-net-core-common-issues"><strong>HTTPClient in .NET Core</strong> &#8211; <strong>Common Issues</strong> </h2>



<p></p>



<p>Let&#8217;s discuss a few issues associated with using HttpClient in the old way.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-resource-exhaustion-problem">Resource Exhaustion Problem</h2>



<p></p>



<p>This was a commonly known issue while using the HTTPClient objects. </p>



<p></p>



<p>Please note that the <strong><em>HTTPClient </em></strong>implements <em><strong>IDisposable</strong></em>.</p>



<p></p>



<p>So basic understanding is to use ‘<strong>using</strong>(..)’ blocks to dispose of the objects but <strong>using </strong>blocks doesn’t release the socket immediately when heavy load operations are performed. Let’s not forget that socket objects are unmanaged resources.</p>



<p></p>



<p><strong>Characteristics and Limitations</strong>:</p>



<p></p>



<ul class="wp-block-list"><li>Each new <strong>HTTPClient </strong>object creates a new socket instance.</li></ul>



<ul class="wp-block-list"><li>Instantiating HTTPClient objects for each request might exhaust the number of sockets available. Example &#8211; <strong>Async</strong> operation with heavy loads.</li></ul>



<ul class="wp-block-list"><li>HTTPClient object doesn’t release the sockets immediately even if it is called using the “using” (<strong>IDisposable</strong>) block.</li></ul>



<ul class="wp-block-list"><li>This may lead to Socket exceptions.</li></ul>



<p></p>



<p>HTTPClient creating using &#8216;new&#8217;  and &#8216;using&#8217; blocks,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices-1024x470.jpg" alt="Create HTTPClient using IHttpClientFactory in ASP.NET Core" class="wp-image-7538" width="498" height="229" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices-1024x470.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices-300x138.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices-768x353.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices-1536x706.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices-785x361.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-ASP.NET-Core-Best-Practices.jpg 1822w" sizes="auto, (max-width: 498px) 100vw, 498px" /></figure>



<p></p>



<p>As per Microsoft guidelines,</p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p><strong>HttpClient</strong>&nbsp;is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new&nbsp;<strong>HttpClient</strong>&nbsp;instance for every request will exhaust the number of sockets available under heavy loads. This will result in&nbsp;<strong>SocketException</strong>&nbsp;errors. </p></blockquote>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices-1024x301.jpg" alt="Create HTTPClient using IHttpClientFactory in ASP.NET Core" class="wp-image-7540" width="496" height="145" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices-1024x301.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices-300x88.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices-768x226.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices-1536x452.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices-785x231.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/HTTPClient-in-.NET-Core-Best-Practices.jpg 1571w" sizes="auto, (max-width: 496px) 100vw, 496px" /></figure>



<p></p>



<p>See <a aria-label="here  (opens in a new tab)" rel="noreferrer noopener" href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client#add-a-model-class" target="_blank"><strong><em>here</em></strong> </a>for more details.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-stale-dns-domain-name-system-problems">Stale DNS (Domain Name System) problems</h2>



<p></p>



<p>As discussed above a Singleton or Static HTTPClient object as specified above should help to resolve the most issues. </p>



<p>But in .NET Core, it was found that  Singleton or Static HTTPClient object doesn&#8217;t respect the DNS update or change in the .NET core.</p>



<p></p>



<p>This is an additional problem that was found in the .NET Core framework. I am not sure if this issue exists in the regular .NET framework </p>



<p>The above common problems can be easily resolved by using HTTPClientfactory introduced recently in .NET Core ( 2.1 and above).</p>



<p></p>



<p>Top 10 benefits pf HttpClientFactory </p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-create-an-http-request-using-httpclientfactory-guidelines">Create an HTTP request using HTTPClientFactory &#8211; Guidelines  </h2>



<p></p>



<p><strong>Create an ASP.NET Core Project</strong></p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/IHttpClientFactory-in-ASP.NET-Core-1024x575.jpg" alt="Create HTTPClient using IHttpClientFactory in ASP.NET Core 5.0" class="wp-image-7508" width="496" height="278"/></figure>



<p></p>



<p>Let&#8217;s look at the basic HttpClient approach where we shall be creating plain HTTPClient using HTTPClientFactory.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-basic-httpclient-request">Basic HTTPClient Request</h2>



<p></p>



<p>You create an HTTPClient object using HTTPClientFactory. </p>



<p>HTTPClientFactory lets you DI inject the HTTPClient objects using an explicit dependency principle. Required instances can be enabled and disabled as required from the API pipeline as middleware.</p>



<p></p>



<p>Update <strong>ConfigureServices </strong>method</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; highlight: [4]; title: ; notranslate">
  public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddHttpClient();
        }

</pre></div>


<p></p>



<p>Once injected HTTpClientFactory from the<strong> Your data Service Constructor</strong>, the instance can be used for creating the HTTPClient object as shown below,</p>



<p></p>



<p>The below example shows <strong>HttpClientFactory </strong>injected through Controller but ideally you can inject it in your DataService model wherever appropriate.</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="568" src="https://www.thecodebuzz.com/wp-content/uploads/2023/06/HttpClientFactory-in-ASPNET-Core-Make-HTTP-requests-using-1024x568.jpg" alt="" class="wp-image-27474" srcset="https://thecodebuzz.com/wp-content/uploads/2023/06/HttpClientFactory-in-ASPNET-Core-Make-HTTP-requests-using-1024x568.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/06/HttpClientFactory-in-ASPNET-Core-Make-HTTP-requests-using-300x166.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/06/HttpClientFactory-in-ASPNET-Core-Make-HTTP-requests-using-768x426.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/06/HttpClientFactory-in-ASPNET-Core-Make-HTTP-requests-using-785x435.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>#image_title</figcaption></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-named-httpclient-request-using-httpclientfactory"><em style="color: revert; font-size: revert; font-weight: revert;">HttpClientFactory</em>  -Named HTTPClient usage with examples</h2>



<p></p>



<p>I have discussed this technique in detail in the below post,</p>



<p></p>



<ul class="has-medium-font-size wp-block-list"><li><a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener"><em>Named HTTPClient using IHttpClientFactory in ASP.NET Core &#8211; Part</em></a><a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener"><em>2</em></a></li></ul>



<p></p>



<p>This technique has an advantage you can configure multiple HTTP clients with custom configuration as required like using <strong><em>policy</em></strong>, <strong>network credentials</strong>, <strong><em>specific header</em>s</strong>, or <em><strong>security</strong></em> tokens as needed.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-typed-httpclient-request-using-httpclientfactory"><em style="color: revert; font-size: revert; font-weight: revert;">HttpClientFactory</em>  -Typed HTTPClient usage with examples </h2>



<p></p>



<p>This is also one of the most <strong>preferred </strong>and easy techniques to create type HTTP Client objects.</p>



<p></p>



<ul class="has-medium-font-size wp-block-list"><li><em><a aria-label=" (opens in a new tab)" rel="noreferrer noopener" href="https://www.thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/" target="_blank">Typed HTTPClient using HttpClientFactory in ASP.NET Core -Part 3</a> </em></li></ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary </h2>



<p></p>



<p>In this article, we looked at how to use HTTPClientFactory for creating HTTPClient request objects to invoke HTTP Services in .NET Core or ASP.NET Core. We saw three basic approaches to creating HTTPClient using HTTPClientFactorylike Basic HTTPClient, Named HTTPClient, and Typed HTTPClient request.</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p> </p>



<p> </p><p>The post <a href="https://thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/">HttpClientFactory in ASP.NET Core with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Configure HttpClientfactory using Autofac DI</title>
		<link>https://thecodebuzz.com/configure-httpclientfactory-autofac-di-httpclient/</link>
					<comments>https://thecodebuzz.com/configure-httpclientfactory-autofac-di-httpclient/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 12 Jan 2021 01:54:00 +0000</pubDate>
				<category><![CDATA[Guidelines]]></category>
		<category><![CDATA[how to use autofac]]></category>
		<category><![CDATA[httpclientfactory class library]]></category>
		<category><![CDATA[httpclientfactory create]]></category>
		<category><![CDATA[httpclientfactory net framework]]></category>
		<category><![CDATA[httpclientfactory without dependency injection]]></category>
		<category><![CDATA[ihttpclientfactory]]></category>
		<category><![CDATA[ioptions autofac]]></category>
		<category><![CDATA[refit autofac]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=14429</guid>

					<description><![CDATA[<p>Configure HttpClientfactory using Autofac DI Today in this article, we will see how to use Configure HttpClientfactory using Autofac DI Container in ASP.NET Core. As we know .NET Core framework has leveraged the Explicit Dependency Injection (DI) principle very well and almost every functionality/service used in the application can be injected through DI. Here Developers have a [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/configure-httpclientfactory-autofac-di-httpclient/">Configure HttpClientfactory using Autofac DI</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Configure HttpClientfactory using Autofac DI</h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="565" height="228" src="https://www.thecodebuzz.com/wp-content/uploads/2021/04/Configure-IHttpClientfactory-using-Autofac-DI-ASP.NET-Core.jpg" alt="Configure HttpClientfactory using Autofac DI" class="wp-image-15508" srcset="https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-IHttpClientfactory-using-Autofac-DI-ASP.NET-Core.jpg 565w, https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-300x121.jpg 300w" sizes="auto, (max-width: 565px) 100vw, 565px" /></figure>



<p>Today in this article, we will see how to use Configure HttpClientfactory using Autofac DI Container in ASP.NET Core.</p>



<p></p>



<p>As we know .NET Core framework has leveraged the <strong><em>Explicit Dependency Injection (DI) </em></strong>principle very well and almost every functionality/service used in the application can be injected through DI.</p>



<p></p>



<p>Here Developers have a choice to use the default DI container framework provided by the application or use a custom <strong><em>DI </em></strong>solution like <strong><em>Autofac </em></strong>etc.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting Started</a></li><li><a href="#aioseo-create-asp-net-core-api">Create ASP.NET Core API</a></li><li><a href="#aioseo-step-1-register-hostbuilder-to-use-autofac-factory">Step 1 &#8211; Register HostBuilder to use Autofac Factory</a></li><li><a href="#aioseo-step-2-define-autofac-di-container-with-httpclientfactory">Step 2 &#8211; Define Autofac DI Container with HttpClientfactory</a></li><li><a href="#aioseo-step-3-use-httpclientfactory-using-dependency-injection">Step 3 – Use HttpClientfactory using Dependency Injection</a></li></ul></div>



<p>Container controls the lifetime of services used and the consumer need not have to worry about disposing of them once after every use.</p>



<p></p>



<p>There are a lot of benefits of the <strong>DI </strong>approach like,</p>



<p></p>



<ul class="wp-block-list">
<li><strong><em>Separation of concern</em></strong></li>



<li><strong><em>Independently deployable unit</em></strong></li>



<li><strong><em>Easily Testable units</em></strong></li>



<li><strong><em>High performance</em></strong></li>



<li><strong><em>Easy maintenance</em></strong></li>
</ul>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting Started</h2>



<p></p>



<ol class="wp-block-list">
<li>Open Visual Studio </li>



<li>Let’s create an&nbsp;<strong>ASP.NET core API application.</strong></li>
</ol>



<p></p>



<h2 class="wp-block-heading" id="aioseo-create-asp-net-core-api">Create ASP.NET Core API</h2>



<p></p>



<p>Please choose any ASP.NET Core API project template. Filters are supported in most ASP.NET Core project templates,</p>



<p></p>



<pre class="wp-block-preformatted"><strong><em>PM> Install-Package Autofac.Extensions.DependencyInjection -Version &lt;version>
</em></strong></pre>



<p>OR</p>



<p>Use <strong><em>Nuget </em></strong>manager,</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="223" src="https://www.thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-1024x223.jpg" alt="" class="wp-image-15509" srcset="https://thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-1024x223.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-300x65.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-768x168.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-1536x335.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-2048x447.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2021/04/IHttpClientfactory-using-Autofac-DI-ASP.NET-Core-785x171.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Configure Autofac DI Container in ASP.NET Core 5.0</figcaption></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step-1-register-hostbuilder-to-use-autofac-factory">Step 1 &#8211; Register HostBuilder to use Autofac Factory</h2>



<p></p>



<p>Register the&nbsp;<strong><em><a href="https://www.thecodebuzz.com/createdefaultbuilder-configuration-management-net-core-and-asp-net-core/" target="_blank" rel="noreferrer noopener">Generic Host Builder</a></em></strong>&nbsp;to use Autofac Factory.</p>



<p></p>



<p>In your <strong><em>Program.cs</em></strong> in the main method please add the <em><strong>UseServiceProviderFactory </strong></em>extension and use the <strong><em>AutofacServiceProviderFactory</em></strong>.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [3,4]; title: ; notranslate">
  public static IHostBuilder CreateHostBuilder(string&#x5B;] args) =&gt;
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =&gt;
                {
                    webBuilder.UseStartup&lt;Startup&gt;();
                });

</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-step-2-define-autofac-di-container-with-httpclientfactory">Step 2 &#8211; Define Autofac DI Container with HttpClientfactory</h2>



<p></p>



<p>Define <strong><em>Autofac </em></strong>DI Container with services as below in&nbsp;<strong><em>Startup</em>.cs</strong></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [5,6]; title: ; notranslate">
  
public void ConfigureContainer(ContainerBuilder builder)
        {
            //Register your services
            builder.RegisterType&lt;BusinessLayer&gt;().As&lt;IBusinessLayer&gt;();
            builder.Register(c =&gt; c.Resolve&lt;IHttpClientFactory&gt;().CreateClient())
            .As&lt;HttpClient&gt;();


        }
</pre></div>


<p></p>



<p>The above code registers the <strong><em>IHttpClientFactory</em></strong> within the Autofac DI container instead of the built-in DI container.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step-3-use-httpclientfactory-using-dependency-injection">Step 3 – Use HttpClientfactory using Dependency Injection</h2>



<p></p>



<p>Please perform dependency Injection (DI) of HttpClientfactory and other required Services using Constructor Injection as shown below,</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="535" src="https://www.thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI-1024x535.jpg" alt="" class="wp-image-15506" srcset="https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI-1024x535.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI-300x157.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI-768x401.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI-1536x802.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI-785x410.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/04/Configure-HttpClientfactory-using-Autofac-DI.jpg 1795w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
    &#x5B;ApiController]
    &#x5B;Route(&quot;&#x5B;controller]&quot;)]
    public class WeatherForecastController : ControllerBase
    {
        private readonly IBusinessLayer _businessLayer;

        private readonly ILogger&lt;WeatherForecastController&gt; _logger;

        private readonly IHttpClientFactory _clientFactory;

        public WeatherForecastController(ILogger&lt;WeatherForecastController&gt; logger, 
                                        IBusinessLayer businessLayer, 
                                        IHttpClientFactory clientFactory)
        {
            _logger = logger;
            _businessLayer = businessLayer;
            _clientFactory = clientFactory;
        }

        &#x5B;HttpGet]
        public async Task&lt;IActionResult&gt; GetAsync()
        {

            var client = _clientFactory.CreateClient(&quot;TheCodeBuzz&quot;);

          ...
          ...
         }
</pre></div>


<p></p>



<p>With the above configuration, you should be all set to use <em><strong>HttpClientfactory </strong></em>using Autofac DI.</p>



<p></p>



<p><strong><em>References </em></strong>: </p>



<p></p>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener" title="Create Named HTTPClient using IHttpClientFactory in ASP.NET Core">Create Named HTTPClient using IHttpClientFactory in ASP.NET Core</a></em></strong></li>



<li><a href="https://www.thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/" target="_blank" rel="noreferrer noopener" title="Typed HTTPClient using HttpClientFactory in ASP.NET Core -Part2"><strong><em>Typed HTTPClient using HttpClientFactory in ASP.NET Core -Part2</em></strong></a></li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/configure-httpclientfactory-autofac-di-httpclient/">Configure HttpClientfactory using Autofac DI</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/configure-httpclientfactory-autofac-di-httpclient/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>HttpClientFactory HTTP GET POST examples</title>
		<link>https://thecodebuzz.com/http-get-post-put-example-using-httpclientfactory/</link>
					<comments>https://thecodebuzz.com/http-get-post-put-example-using-httpclientfactory/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 18 Apr 2020 04:45:02 +0000</pubDate>
				<category><![CDATA[Tips and Guidelines]]></category>
		<category><![CDATA[addhttpclient example]]></category>
		<category><![CDATA[configureprimaryhttpmessagehandler]]></category>
		<category><![CDATA[httpclientfactory .net framework example]]></category>
		<category><![CDATA[httpclientfactory postasync]]></category>
		<category><![CDATA[httpclientfactory source code]]></category>
		<category><![CDATA[httpclientfactory vs httpclient]]></category>
		<category><![CDATA[httpclientfactory without dependency injection]]></category>
		<category><![CDATA[httpclientfactory.createclient example]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=9580</guid>

					<description><![CDATA[<p>Http GET, POST, PUT and DELETE example using HttpClientFactory In today’s post, we will see the HttpClientFactory HTTP GET POST examples. We shall create a basic or named HttpClient instance. In this instance, we shall use HTTP GET, POST PUT, or DELETE methods. Today in this article, we will cover below aspects, In our previous [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/http-get-post-put-example-using-httpclientfactory/">HttpClientFactory HTTP GET POST examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Http GET, POST, PUT and DELETE example using HttpClientFactory</h1>



<p>In today’s post, we will see the HttpClientFactory HTTP GET POST examples. We shall create a basic or named HttpClient instance. </p>



<p></p>



<p>In this instance, we shall use HTTP GET, POST PUT, or DELETE methods.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-calling-the-get-method-using-httpclientfactory">Calling the GET method using HttpClientFactory</a></li><li><a href="#aioseo-calling-the-post-method-using-httpclientfactory">Calling the POST method using HttpClientFactory</a></li><li><a href="#aioseo-calling-the-put-method-using-httpclientfactory">Calling the PUT method using HttpClientFactory</a></li><li><a href="#aioseo-calling-the-delete-method-using-httpclientfactory">Calling the DELETE method using HttpClientFactory</a></li></ul></div>



<p></p>



<p>In our previous article, we already also looked at approaches to create <strong>HTTPClient </strong>requests in <strong>ASP.NET Core</strong> API.</p>



<p></p>



<ul class="wp-block-list">
<li><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/" target="_blank"><strong><em>Basic HTTPClient</em></strong></a></li>



<li><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank"><strong><em>Named HTTPClient</em></strong></a></li>



<li><a rel="noreferrer noopener" href="https://www.thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/" target="_blank"><strong><em>Typed HTTPClient</em></strong></a></li>
</ul>



<p></p>



<p>Let’s look at a few examples to invoke HTTP GET and POST methods using <strong>HttpClientfactory</strong>.</p>



<p></p>



<p>As discussed in the previous article I have already setup the <a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener">named HttpClientclientFactory</a> to create the required HttpClient instance as below,</p>



<p></p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="975" height="277" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/Post-example-httpclientfactory-.net-core-csharp.jpg" alt="HttpClientFactory GET, POST, PUT and DELETE example " class="wp-image-9581" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/Post-example-httpclientfactory-.net-core-csharp.jpg 975w, https://thecodebuzz.com/wp-content/uploads/2020/04/Post-example-httpclientfactory-.net-core-csharp-300x85.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/Post-example-httpclientfactory-.net-core-csharp-768x218.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/Post-example-httpclientfactory-.net-core-csharp-785x223.jpg 785w" sizes="auto, (max-width: 975px) 100vw, 975px" /></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-calling-the-get-method-using-httpclientfactory">Calling the GET method using HttpClientFactory </h2>



<p></p>



<p>Below is a sample GET method that shows creating a named instance of HttpClient using HttpClientFactory and invoking the GET method asynchronously.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [6]; title: ; notranslate">
        //GET:  api/Accounts/PersonalAccounts/1234
        &#x5B;HttpGet]
        &#x5B;Route(&quot;PersonalAccounts&quot;)]
        public async Task&lt;IActionResult&gt; GetAccountDetails(int employeeId)
        {
            var client = _clientFactory.CreateClient(&quot;AccountClient&quot;);

            var response = await client.GetAsync($&quot;api/accounts/PersonalAccounts/{employeeId}&quot;);

            if (response.IsSuccessStatusCode)
            {
                return Ok(response.Content.ReadAsStreamAsync().Result);
            }
            else
            {
                return StatusCode(500, &quot;Something Went Wrong! Error Occured&quot;);
            }
        }
</pre></div>


<p></p>



<p>In the above example, we are using the <em><strong>IHttpClientFactory </strong></em>instance to create a client. Using generated client we invoke the GET call for the given Uri and return the result.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-calling-the-post-method-using-httpclientfactory">Calling the POST method using HttpClientFactory</h2>



<p></p>



<p>Below is a sample <strong>POST </strong>method example. Here I am creating a named instance of <strong>HttpClient </strong>using <strong>HttpClientFactory </strong>and invoking the POST <a href="https://www.thecodebuzz.com/moq-to-mock-asynchronous-method-net-core-unit-tests/">method asynchronously</a>. </p>



<p></p>



<p><strong>Note: Below samples are shown using direct usage of post-call in Controller. Ideally please structure your code considering the separation of code.</strong></p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1022" height="394" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/Http-Post-example-httpclientfactory-.net-core-csharp.jpg" alt="GET, POST, PUT and DELETE example " class="wp-image-9731" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/Http-Post-example-httpclientfactory-.net-core-csharp.jpg 1022w, https://thecodebuzz.com/wp-content/uploads/2020/04/Http-Post-example-httpclientfactory-.net-core-csharp-300x116.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/Http-Post-example-httpclientfactory-.net-core-csharp-768x296.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/Http-Post-example-httpclientfactory-.net-core-csharp-785x303.jpg 785w" sizes="auto, (max-width: 1022px) 100vw, 1022px" /></figure>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Ideally, the POST method should also return the location of newly created resources as per REST guidelines.</p>
</blockquote>



<p></p>



<h2 class="wp-block-heading" id="aioseo-calling-the-put-method-using-httpclientfactory">Calling the PUT method using HttpClientFactory</h2>



<p></p>



<p>Below is a sample <strong>PUT</strong> method using <strong>HttpClientFactory </strong>and invoking the Put method asynchronously. </p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [7]; title: ; notranslate">
        //PUT:  api/Accounts/1234
        &#x5B;HttpPut]
        public async Task&lt;IActionResult&gt; Put(int employeeId, Customer customer)
        {
            CusotmerDetails employeeDetails = null;

            var client = _clientFactory.CreateClient(&quot;AccountClient&quot;);

            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(customer)
                , Encoding.UTF8, &quot;application/json&quot;);

            HttpResponseMessage response = await client.PutAsync($&quot;api/accounts/{employeeId}&quot;, httpContent);

            if (!response.IsSuccessStatusCode)
            {
                return StatusCode(500, &quot;Something Went Wrong! Error Occured&quot;);
            }

            employeeDetails = JsonConvert.DeserializeObject&lt;CusotmerDetails&gt;(response.Content.ReadAsStringAsync().Result);

            return Ok(employeeDetails);
        }
</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-calling-the-delete-method-using-httpclientfactory">Calling the DELETE method using HttpClientFactory</h2>



<p></p>



<p>Below is a sample example for DELETE using HttpClientFactory. Below we are using HttpClientFactory and invoking the method asynchronously.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [7]; title: ; notranslate">
        //DELETE:  api/Accounts/1234
        &#x5B;HttpDelete]
        public async Task&lt;IActionResult&gt; Delete(int employeeId)
        {
            CusotmerDetails employeeDetails = null;

            var client = _clientFactory.CreateClient(&quot;AccountClient&quot;);

            HttpResponseMessage response = await client.DeleteAsync($&quot;api/accounts/{employeeId}&quot;);

            if (!response.IsSuccessStatusCode)
            {
                return StatusCode(500, &quot;Something Went Wrong! Error Occured&quot;);
            }

            employeeDetails = JsonConvert.DeserializeObject&lt;CusotmerDetails&gt;(response.Content.ReadAsStringAsync().Result);

            return Ok(employeeDetails);
        }
</pre></div>


<p></p>



<p><strong><em>References</em></strong>:</p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/" target="_blank" rel="noreferrer noopener"><strong><em>Using HTTPClient Best Practices and Anti-Patterns</em></strong></a></li>
</ul>



<p></p>



<p> </p>



<p>That&#8217;s all! Happy Coding!</p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/http-get-post-put-example-using-httpclientfactory/">HttpClientFactory HTTP GET POST examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/http-get-post-put-example-using-httpclientfactory/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Typed HTTPClient using HttpClientFactory in ASP.NET Core &#8211; Part2</title>
		<link>https://thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/</link>
					<comments>https://thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 25 Jan 2020 20:25:31 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[asp.net core 2.1 httpclientfactory]]></category>
		<category><![CDATA[asp.net core 3.0 httpclientfactory]]></category>
		<category><![CDATA[asp.net core 3.1 httpclientfactory]]></category>
		<category><![CDATA[autofac httpclientfactory]]></category>
		<category><![CDATA[HTTPClient best practices]]></category>
		<category><![CDATA[HTTPClientFactory add authentication]]></category>
		<category><![CDATA[HTTPClientFactory add basic auth headers]]></category>
		<category><![CDATA[HTTPClientFactory add headers]]></category>
		<category><![CDATA[HTTPClientFactory add JWT bearer]]></category>
		<category><![CDATA[httpclientfactory c#]]></category>
		<category><![CDATA[HTTPClientFactory certificates]]></category>
		<category><![CDATA[httpclientfactory console app]]></category>
		<category><![CDATA[httpclientfactory createclient]]></category>
		<category><![CDATA[httpclientfactory example]]></category>
		<category><![CDATA[httpclientfactory github]]></category>
		<category><![CDATA[httpclientfactory in class library]]></category>
		<category><![CDATA[httpclientfactory net framework]]></category>
		<category><![CDATA[httpclientfactory typed client]]></category>
		<category><![CDATA[httpclientfactory without dependency injection]]></category>
		<category><![CDATA[ihttpclientfactory net core]]></category>
		<category><![CDATA[Resources Exhaustion DNS problem]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=7551</guid>

					<description><![CDATA[<p>Typed HTTPClient using HttpClientFactory in ASP.NET Core In today’s post, we will see how to create typed HTTPClient requests using HTTPClientFactory in .NET Core or ASP.NET Core. In our last article, we understood the Differences between HTTPClient and HTTPClientFactory and also learned the Best practices for using HTTPClientFactory to create an HTTPClient object addressing the [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/">Typed HTTPClient using HttpClientFactory in ASP.NET Core – Part2</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Typed HTTPClient using HttpClientFactory in ASP.NET Core </h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="408" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/typed-http-client-HttpClientFactory-in-ASP.NET-Core-Best-Practices.jpg" alt="HttpClientFactory in ASP.NET Core " class="wp-image-7557" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/typed-http-client-HttpClientFactory-in-ASP.NET-Core-Best-Practices.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-http-client-HttpClientFactory-in-ASP.NET-Core-Best-Practices-300x120.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-http-client-HttpClientFactory-in-ASP.NET-Core-Best-Practices-768x306.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-http-client-HttpClientFactory-in-ASP.NET-Core-Best-Practices-785x313.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In today’s post, we will see how to create typed HTTPClient requests using <strong>HTTPClientFactory </strong>in .NET Core or ASP.NET Core.</p>



<p></p>



<p>In our last article, we understood the <a href="https://www.thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener"><em><strong>Differences between HTTPClient and HTTPClientFactory</strong></em></a> and also learned the Best practices for using <strong>HTTPClientFactory </strong>to create an HTTPClient object addressing the known issues of HTTPClient usage in the traditional way in ASP.NET Core.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-create-typed-httpclient">Create Typed HTTPClient</a></li><li><a href="#aioseo-typed-httpclient-via-controller-di">Typed HTTPClient via Controller DI</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p>In our previous article, we already also looked at <a href="https://www.thecodebuzz.com/httpclient-using-httpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Basic HTTPClient</em></strong></a> and <a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Named HTTPClient </em></strong></a>approaches to create <strong>HTTPClient </strong>requests using a similar concept.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-create-typed-httpclient">Create Typed HTTPClient</h2>



<p></p>



<p>Let’s look at the step by step to understand and create a Typed HTTPClient approach where we shall be creating typed HTTPClient using the IHTTPClientFactory interface.</p>



<p></p>



<p><strong>Create an ASP.NET Core Project</strong></p>



<p></p>



<figure class="wp-block-image is-resized"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/IHttpClientFactory-in-ASP.NET-Core-1024x575.jpg" alt="HttpClientFactory in ASP.NET Core 5.0" class="wp-image-7508" style="width:497px;height:278px"/></figure>



<p></p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Add using namespace ‘System.Net.Http’ in the code to access HTTPClient and IHTTPClientFactory</p>
</blockquote>



<p></p>



<p>Please update the&nbsp;<strong>ConfigureServices&nbsp;</strong>method in <em><strong>Startup.cs</strong></em> as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            
            //Create Typed client
            services.AddHttpClient&lt;AccountClient&gt;();
         }
</pre></div>


<p></p>



<p>Below is our typed HTTPClient i.e <strong>AccountClient </strong>implementation </p>



<p></p>



<p><strong>AccountClient</strong> class here not just addressing basic class responsibility. It is mainly addressing HttpClient creation through DI. This class will make sure you get the best available HttpClient object from the pool and address your calls.</p>



<p></p>



<p>Defining AccountClient using <strong><em>services.AddHttpClient </em></strong>will let you attach any specific requirements like a custom header <a href="https://www.thecodebuzz.com/configure-certificate-with-httpclient-authentication/" target="_blank" rel="noreferrer noopener" title="Configure Certificate with HttpClient Authentication">certificate </a>or <a href="https://www.thecodebuzz.com/httpclienthandler-client-certificate-basic-auth-httpclientfactory/" target="_blank" rel="noreferrer noopener" title="How to use HttpClientHandler with HttpClientFactory">compression</a> logic easily. </p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public class AccountClient
    {
        private readonly HttpClient _client;
        private readonly IConfiguration _configuration;
        public AccountClient(HttpClient client, IConfiguration configuration)
        {
            _client = client;
            _configuration = configuration;
        }
        public async Task&lt;string&gt;GetAccount()
        {
            var uri = new Uri(_configuration.GetValue&lt;string&gt;(&quot;AccountURL&quot;));
            var response = await _client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                return null;
            }
           
        }
    }
</pre></div>


<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-typed-httpclient-via-controller-di">Typed HTTPClient via Controller DI </h2>



<p></p>



<p>Once defined the typed HTTPClient <strong>AccountClient</strong> can be injected from the Constructor in any other module or class where we need to call HTTP services.</p>



<p></p>



<p>This instance can be used for invoking the required operations as shown below, </p>



<p>Below is an example using Controller but ideally your actual implementation, you might call it in Service layer or Data access layer,or Infra layer.</p>



<p></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="577" src="https://www.thecodebuzz.com/wp-content/uploads/2020/01/typed-httpclient-IHttpClientFactory-in-ASP.NET-Core-1024x577.jpg" alt="Typed HTTPClient using HTTPClientFactory " class="wp-image-7513" srcset="https://thecodebuzz.com/wp-content/uploads/2020/01/typed-httpclient-IHttpClientFactory-in-ASP.NET-Core-1024x577.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-httpclient-IHttpClientFactory-in-ASP.NET-Core-300x169.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-httpclient-IHttpClientFactory-in-ASP.NET-Core-768x433.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-httpclient-IHttpClientFactory-in-ASP.NET-Core-785x443.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/01/typed-httpclient-IHttpClientFactory-in-ASP.NET-Core.jpg 1403w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p><strong>AccountClient </strong>will be available to use in every class/module in a project as required.  Lifetime management of injected <strong>HTTPClient </strong>instances will be done through the API pipeline itself. </p>



<p></p>



<p>Additionally, this technique lets you control and configure HTTPClient&#8217;s request with custom configuration of&nbsp;<strong>Policy, Security,&nbsp;</strong>or <strong>delegates&nbsp;</strong>as required. </p>



<p></p>



<p><strong><em>References: </em></strong></p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/" title="Using HTTPClient Best Practices and Anti-Patterns" target="_blank" rel="noreferrer noopener"><strong><em>Using HTTPClient Best Practices and Anti-Patterns</em></strong></a></li>



<li><a href="https://www.thecodebuzz.com/create-named-httpclient-ihttpclientfactory-asp-net-core/" target="_blank" rel="noreferrer noopener" title="Create Named HTTPClient using IHttpClientFactory in ASP.NET Core"><strong><em>Create Named HTTPClient using IHttpClientFactory in ASP.NET Core</em></strong></a></li>
</ul>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary</h2>



<p></p>



<p>In this article, we looked at how to use HTTPClientFactory to create a <strong>Typed HTTPClient </strong>request object to invoke HTTP services in ASP.NET Core. This technique also lets you control lifetime and configure HTTPClient&#8217;s request with custom <strong>Policy, Security, </strong>or <strong>delegates </strong>as required. </p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/">Typed HTTPClient using HttpClientFactory in ASP.NET Core – Part2</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/typed-httpclient-using-httpclientfactory-in-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
