Introduction
Integrating external APIs into a .NET MAUI application allows you to enrich your mobile, desktop, and web experiences with data and services from the cloud. This guide walks through best practices, common patterns, and sample code for consuming RESTful services, handling authentication, and managing network reliability.
1. Setting Up HttpClient
Use a singleton HttpClient
to avoid socket exhaustion. Register it with the built‑in DI container.
using Microsoft.Extensions.DependencyInjection;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.Services.AddHttpClient("ApiClient", client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
return builder.Build();
}
}
2. Consuming a GET Endpoint
Define a typed service that fetches data from the API.
public interface IWeatherService
{
Task<WeatherForecast> GetForecastAsync(string city);
}
public class WeatherService : IWeatherService
{
private readonly HttpClient _http;
public WeatherService(IHttpClientFactory factory)
{
_http = factory.CreateClient("ApiClient");
}
public async Task<WeatherForecast> GetForecastAsync(string city)
{
var response = await _http.GetAsync($"/weather/forecast?city={city}");
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<WeatherForecast>();
}
}
3. Registering the Service
builder.Services.AddTransient<IWeatherService, WeatherService>();
4. Using the Service in a ViewModel
public partial class WeatherViewModel : ObservableObject
{
[ObservableProperty]
private string city;
[ObservableProperty]
private WeatherForecast forecast;
private readonly IWeatherService _weatherService;
public WeatherViewModel(IWeatherService weatherService)
{
_weatherService = weatherService;
City = "Seattle";
}
[RelayCommand]
private async Task LoadForecast()
{
Forecast = await _weatherService.GetForecastAsync(City);
}
}
5. Handling Authentication (OAuth2)
Use IdentityModel.OidcClient
or MSAL for token acquisition. Below is a minimal example with MSAL.
builder.Services.AddSingleton<IPublicClientApplication>(sp =>
PublicClientApplicationBuilder.Create("YOUR_CLIENT_ID")
.WithRedirectUri($"msal{YOUR_CLIENT_ID}://auth")
.Build());
builder.Services.AddTransient<IAuthService, MsalAuthService>();
6. Resilience with Polly
Add retry and circuit‑breaker policies to the HttpClient.
builder.Services.AddHttpClient("ApiClient")
.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ =>
TimeSpan.FromSeconds(2)))
.AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
7. Platform‑Specific Considerations
- iOS & Android: Add the appropriate network security configuration (App Transport Security for iOS, cleartext traffic for Android if needed).
- Windows: Ensure
Internet (Client)
capability is enabled in the manifest. - macOS: Use
NSAppTransportSecurity
settings if communicating with non‑HTTPS endpoints (not recommended).
Conclusion
By combining HttpClient
, DI, authentication libraries, and resilience policies, you can build robust API‑driven .NET MAUI apps that work seamlessly across all supported platforms.