79421625

Date: 2025-02-07 16:57:03
Score: 2
Natty:
Report link

I am using .NET 8 and developing a .NET MAUI Blazor Hybrid app which connects with my ASP.NET API

What our uncle Bill suggests (and works great) is to create an API Service:

Create your service class:

public class APIService : IAPIService
 {
     HttpClient _httpClient;
     JsonSerializerOptions _jsonSerializerOptions;
     Uri _baseURI;
     public APIService()
     {
         _httpClient = new HttpClient();
         _jsonSerializerOptions = new JsonSerializerOptions
         {
             PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
             WriteIndented = true,
         };
         _baseURI = new Uri("https://localhost:7148");
     }

     public async Task<bool> POSTCredentialsAsync(LoginCommand command)
     {
         var response = await _httpClient.PostAsJsonAsync(_baseURI + "/login", command);
         if (response.IsSuccessStatusCode)
         {
             return true;
         }
         return false;
     }

     public async Task<bool> POSTRegistrationAsync(RegisterMarket command)
     {
         var response = await _httpClient.PostAsJsonAsync(_baseURI + "/register", command);
         if (response.IsSuccessStatusCode)
         {
             return true;
         }
         return false;
     }
 }

like that above.

A Interface (for dependency injection in pages, blazor pages uses @Inject):

  internal interface IAPIService
  {
      public Task<bool> POSTCredentialsAsync(LoginCommand command);
      public Task<bool> POSTRegistrationAsync(RegisterMarket command);
  }

Lastly, in MauiProgram.cs

  builder.Services.AddScoped<IAPIService, APIService>();

Works really well in my apps

And you can handle the responses in another source file Hope it helps Thanks in advance

Microsoft oficial reference: https://learn.microsoft.com/en-us/dotnet/maui/data-cloud/rest?view=net-maui-9.0

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Whitelisted phrase (-1): Hope it helps
  • RegEx Blacklisted phrase (3): Thanks in advance
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Athanor