C# HttpClient and IHttpClientFactory in .net core

The C# HttpClient is the go-to library when you need to GET, PUT, POST or DELETE from an API Endpoint. But one of the issues with HttpClient is that it needs to be instantiated as a singleton. This is a big no-no:

public static async Task<string> Get(string queryString)
{
  using (var httpClient = new HttpClient())
  {
    using (var result = await httpClient.GetAsync($"https://briancaos.wordpress.com"))
	{
	  string content = await result.Content.ReadAsStringAsync();
	  return content;
	}
  }
}

The HttpClient is a shared object, and disposing the HttpClient for each call will lead to socket exhaustion.

SO WHAT TO DO THEN?

The trick is to use a IHttpClientFactory. This will create static instances for you (as well as allowing you to use Polly and other middlewares, but that’s a story for another time).

It’s very easy to use:

STEP 1: INSTANTIATE AN IHttpClientFactory AT STARTUP:

To instantiate an IHttpClientFactory, use builder.Services.AddHttpClient:

var builder = WebApplication.CreateBuilder(webApplicationOptions);
...
builder.Services.AddHttpClient("HttpClient");
...
var app = builder.Build();
await app.RunAsync();

The IHttpClientFactory is named, and you can have several IHttpClientFactory instances, each with their own name. If you don’t know why you should have more then one, then you don’t need more than one.

STEP 2: INJECT THE IHttpClientFactory INTO YOUR CONSTRUCTOR

This is the basics of how your repository should look:

namespace MyCode
{
  public class MyRepository
  {
    private IHttpClientFactory _httpClientFactory;

    public MyRepository(IHttpClientFactory httpClientFactory)
    {
      _httpClientFactory = httpClientFactory;
    }

    public async Task<string> GetAsync(string url)
    {
      var client = _httpClientFactory.CreateClient("HttpClient");

      var response = await client.GetAsync($"{url}");
      if (!response.IsSuccessStatusCode)
        throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}");
      var response = await response.Content.ReadAsStringAsync();
	  return response;
    }
  }
}

The _httpClientFactory.CreateClient(“HttpClient”); will ensure that you reuse the httpclient already created at startup.

That’s it. You are now a HttpClient expert. Happy coding.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , . Bookmark the permalink.

2 Responses to C# HttpClient and IHttpClientFactory in .net core

  1. Pingback: C# Use HttpClient to GET JSON from API endpoint | Brian Pedersen's Sitecore and .NET Blog

  2. Ken says:

    Nice article! Short and to the point, just the way they should be. This way of working with the IHTTPClientFactory makes it way easier to test the methods.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.