Iv been reading alot about HttpClient and realized that I had to change our implementation of our RestHandler due to we were instantiating a new HttpClient object for each request. We use alot of request for our RestHandler (using HttpClient).
Questions:
Now the implementation looks something like this:
public class RestHandler : IRestHandler
{
private static readonly HttpClient HttpClient = new HttpClient();
public RestHandler()
{
//HttpClient.DefaultRequestHEaders.Authorization = new AuthenticationHeaderValue(some logic);
//HttpClient.DefaultRequestHEaders.Add("id","customId");
}
public async Task<GenericResult<T>> GetResultAsync<T>(string url) where T : new()
{
var response = await HttpClient.GetAsync(url);
var result = await response.Content.ReadAsAsync<T>();
return new GenericResult<T> { HttpResponseMessage = response, Result = result};
}
}
public interface IRestHandler
{
Task<GenericResult<T>> GetResultAsync<T>(string url) where T : new();
}
public class GenericResult<T> where T : new()
{
public T Result { get; set; }
public HttpResponseMessage HttpResponseMessage { get; set; }
}
Best regards Robert
Read this: You're using httpClient wrong and it's destabilizing your software
It talks about how HttpClient is truly reentrant and thread-safe. It also proves its case for why you should be using one single HttpClient for the entire application.
What you're doing looks fine to me.
As an aside, I've personally had problems with HttpClient and Mono. We use RestSharp and prefer it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.