I tried use a Base Class, but then I went around in circles trying to call HttpContext from static class, etc...I've looked for examples but there is so much noise online re: HttpClient or HttpClient Factory, I don't know where to start.
I feel a base class makes the DI code overly complex. Use standard DI service patterns and C# generics. Your service interface will have GET, POST, PUT, DELETE, etc. and perhaps a few method overloads loads.
For example
public interface IApiService
{
Task<T> GetAsync<T>(string accessToken, string restApi);
}
public async Task<T> GetAsync<T>(string accessToken, string restApi)
{
_logger.LogDebug($"Api = {restApi}");
T results = (T)Activator.CreateInstance(typeof(T));
var client = _httpClientFactory.CreateClient(_apiFactoryName);
if (!string.IsNullOrEmpty(accessToken))
{
client.SetBearerToken(accessToken);
}
using (Stream s = await client.GetStreamAsync($"{restApi}"))
{
using (StreamReader sr = new StreamReader(s))
{
using (JsonReader reader = new JsonTextReader(sr))
{
JsonSerializer serializer = new JsonSerializer();
results = serializer.Deserialize<T>(reader);
}
}
}
return results;
}
Your POST implementation will also have input models.
All-Star
52201 Points
23274 Posts
Re: Reusable HttpClient
Nov 21, 2020 03:41 PM|mgebhard|LINK
Use DI to configure HttpClient. If you have multiple services then create a factory. These concepts are covered in official documentation.
https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0
I feel a base class makes the DI code overly complex. Use standard DI service patterns and C# generics. Your service interface will have GET, POST, PUT, DELETE, etc. and perhaps a few method overloads loads.
For example
Your POST implementation will also have input models.