HttpClient Usage
The correct usage of the HttpClient class.
Calling / using the HttpClient class in the following manner may seem like the obvious way to use it.
using (var client = new HttpClient()) { // use the client object }
However, this could result in a “Circuit Exhaustion” error when volume or load is increased.
The following is the correct, recommended usage.
- Add a reference to the “Microsoft.Extensions.Http” package, which includes the IHttpClientFactory interface.
- In the main method, use dependency inject to obtain an instance of the “IHttpClientFactory” interface.
static async Task Main(string[] args) { var serviceProvider = new ServiceCollection() .AddHttpClient() .BuildServiceProvider(); // Save this to a variable that can be retrieved / used later. var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>(); }
- To create an HTTP client using the factory, you can use the CreateClient method and specify a name for the client:
var client = httpClientFactory.CreateClient("myClient");
- Use the client to send an HTTP request and receive a response:
var response = await client.GetAsync("https://www.example.com"); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); }
- Dispose of the client when you're finished with it:
client.Dispose();
- Alternatively, you can use a using block to automatically dispose of the client when it goes out of scope:
using (var client = httpClientFactory.CreateClient("myClient")) { var response = await client.GetAsync("https://www.example.com"); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } }