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