最佳答案
WebAPI 客户端的 HttpClient
生命周期应该是多少?
对于多个调用,使用一个 HttpClient
实例是否更好?
每个请求创建和处理一个 HttpClient
的开销是多少,如下面的例子(取自 http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client) :
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}