Using HttpClient in CustomApiClient

17 hours ago 2
ARTICLE AD BOX

I'm working on a custom ApiClient that I'll be using both in my .NET MAUI and Blazor WASM apps. The primary purpose of the ApiClient is to facilitate calls to my API using HttpClient.

The challange here is that Blazor and .NET MAUI handle HttpClient's differently. In Blazor, we can use IHttpClientFactory but in .NET MAUI the recommended approach is to create the HttpClient within the service class -- see Microsoft Doc: https://learn.microsoft.com/en-us/dotnet/maui/data-cloud/rest?view=net-maui-10.0#create-the-httpclient-object

My question then is how to design my ApiClient so that it can be used in both .NET MAUI and Blazor apps and receive HttpClient in a way that is right for the platform.

Here's one approach I can think of though I'm not sure if it's a good one. I simply pass the IHttpClientFactory that I inject into my DI container along with a bool value indicating whether the app is a mobile -- .NET MAUI -- app or not. If the app is a Blazor app, meaning the isMobile is set to false, I use the IHttpClientFactory to handle the HttpClient.

And if the isMobile is set to true, the IHttpClientFactory would be null and I'd use the HttpClient declared locally.

public class MyApiClient { HttpClient _client; HttpClientFactory _httpClientFactory; public MyApiClient(IHttpClientFactory httpClientFactory, bool isMobile) { if(isMobile && httpClientFactory is null) _client = new HttpClient(); else _httpClientFactory = httpClientFactory; } public async Task<T> GetAsync<T>(string url) { if(isMobile) { // Use _client declared at class level } else { using(var client = _httpClientFactory.CreateClient("MyApiClient"); { // Use the client managed by IHttpCilentFactory } } } }

As I said, I'm not quite happy with this approach but that's the best I have so far. I'd appreciate any suggestions you may have. Thanks!

Read Entire Article