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:
- Add a UserAgent to the IHttpClientFactory in .NET Core from briancaos
- HttpClient retry on HTTP timeout with Polly and IHttpClientBuilder from briancaos
- HttpClient retry mechanism with .NET Core, Polly and IHttpClientFactory from briancaos
- Using C# HttpClient from Sync and Async code from briancaos
- YOU’RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE by Simon Timms
- Improper Instantiation antipattern from Microsoft
- Make HTTP requests using IHttpClientFactory in ASP.NET Core from Microsoft
Pingback: C# Use HttpClient to GET JSON from API endpoint | Brian Pedersen's Sitecore and .NET Blog
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.
LikeLike