Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Using HttpClient in CustomApiClient

$
0
0

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 REST 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 MyApiClient 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 in the case of .NET MAUI apps, the isMobile is set to true, the IHttpClientFactory would be null and I'd use the HttpClient declared locally.

public class MyApiClient{   HttpClient _client;   IHttpClientFactory _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 IHttpClientFactory           }       }   }}

As I said, I'm not quite happy with this approach but that's the best I have so far. One not-so-clean aspect of this approach is that my client will need the Microsoft.Extensions.Http NuGet package in order to use IHttpClientFactory and in the case of .NET MAUI apps, that's one unnecessary package that will only bloat MyApiClient.

I'd appreciate any suggestions you may have. Thanks!


Viewing all articles
Browse latest Browse all 4839

Trending Articles