我正在使用HttpClient的单例实例进行调用。我想知道有没有办法测试HttpClient是否有效?在应用程序的生命周期中,这个HttpClient实例是否会变坏,因为需要创建一个新实例。我的代码如下
public class HttpClientWrapper : IHttpClientWrapper
{
private Uri _baseAddress;
private int _connectionTimeout;
private HttpClient _httpClientInstance;
private HttpClient HttpClientInstance
{
get
{
if (_httpClientInstance == null)
_httpClientInstance = CreateHttpClient();
return _httpClientInstance;
}
}
public HttpClientWrapper(Uri baseAddress, int connectionTimeout)
{
_baseAddress = baseAddress;
_connectionTimeout = connectionTimeout;
}
public Task<HttpResponseMessage> PostAsJsonAsync<T>(string requestUri, T value)
{
//Test the instance before using it. What should be the test??
return HttpClientInstance.PostAsJsonAsync<T>(requestUri, value);
}
private HttpClient CreateHttpClient()
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true
};
HttpClient client = new HttpClient(handler);
client.Timeout = TimeSpan.FromMilliseconds(_connectionTimeout);
client.BaseAddress = _baseAddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
}
答案 0 :(得分:0)
HttpClient旨在重用。它与WCF和ChannelFactory的旧时代不同,其中频道可能处于故障状态并且必须重新创建。
HttpClient 旨在实例化一次并在应用程序的整个生命周期中重复使用。特别是在服务器应用程序中,为每个请求创建一个新的HttpClient实例将耗尽重负载下可用的套接字数量。这将导致SocketException错误。
参考:https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client