For production C# apps, follow these best practices with HttpClient
.
🏗️ Use IHttpClientFactory (ASP.NET Core)
1
2
3
4
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
Inject IHttpClientFactory
into your service:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyService
{
private readonly HttpClient _client;
public MyService(HttpClient client)
{
_client = client;
}
public async Task<string> GetDataAsync()
{
var response = await _client.GetAsync("https://api.example.com/data");
return await response.Content.ReadAsStringAsync();
}
}
🔁 Reuse HttpClient
- In console apps, keep a single
HttpClient
instance for the app’s lifetime. - Avoid creating new
HttpClient
per request to prevent socket exhaustion.
🛠️ Handling Errors
- Always check
response.IsSuccessStatusCode
. - Use try/catch around your API calls.
Next: Sending requests and handling responses!