I have a web application that pulls data from an API using the HttpClient class. I have a few questions.
using (HttpClient client = new HttpClient()) for each request?Try to find best and optimal solution.
Yes, HttpClient is certainly appropriate for using web APIs and deserialization.
Creating a new HttpClient for each request is not a good usage. The recommended way is to create HttpClient objects using the IHttpClientFactory interface. Here is a basic usage from MSDN:
class TodoService
{
private readonly IHttpClientFactory _httpClientFactory = null!;
private readonly ILogger<TodoService> _logger = null!;
public TodoService(
IHttpClientFactory httpClientFactory,
ILogger<TodoService> logger) =>
(_httpClientFactory, _logger) = (httpClientFactory, logger);
public async Task<Todo[]> GetUserTodosAsync(int userId)
{
// Create the client
using HttpClient client = _httpClientFactory.CreateClient();
try
{
// Make HTTP GET request
// Parse JSON response deserialize into Todo types
Todo[]? todos = await client.GetFromJsonAsync<Todo[]>(
$"https://jsonplaceholder.typicode.com/todos?userId={userId}",
new JsonSerializerOptions(JsonSerializerDefaults.Web));
return todos ?? Array.Empty<Todo>();
}
catch (Exception ex)
{
_logger.LogError("Error getting something fun to say: {Error}", ex);
}
return Array.Empty<Todo>();
}
}
}
You can refer to IHttpClientFactory with .NET and Guidelines for using HttpClient
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With