我有一个 Web 应用程序,它使用 HttpClient 类从 API 中提取数据。我有几个问题。
- HttpClient 是从 API 获取数据的最佳选择吗?我从 APi 获取一个字符串并将其反序列化为一个对象。
- 每次使用时都会创建 HttpClient 的新实例(针对每个用户)。最好使用:
using (HttpClient client = new HttpClient())
对于每个请求?
尝试找到最佳和最优的解决方案。
-
Yes, HttpClient
当然适合使用 Web API 和反序列化。
-
创建一个新的HttpClient
对于每个请求都不是一个好的用法。推荐的方法是创建HttpClient
对象使用IHttpClientFactory
界面。以下是来自 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>();
}
}
}
您可以参考IHttpClientFactory 与 .NET
and
HttpClient 使用指南
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)