HttpClient in .NET MAUI
Making network requests is a fundamental part of many mobile applications. .NET MAUI leverages the robust HttpClient
class from the .NET ecosystem to handle these operations efficiently.
Introduction to HttpClient
HttpClient
is a modern, flexible, and powerful class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. It's designed to be instantiated once and reused throughout the life of an application.
Basic GET Request
To fetch data from a remote API, you typically use a GET request. Here's a simple example using HttpClient
in a .NET MAUI application:
using System.Net.Http;
using System.Threading.Tasks;
public class ApiService
{
private readonly HttpClient _httpClient;
public ApiService()
{
// Instantiate HttpClient once and reuse it.
// Consider injecting this via dependency injection in real applications.
_httpClient = new HttpClient();
// Set a base address if all requests share a common root
_httpClient.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
}
public async Task<string> GetDataAsync(string endpoint)
{
try
{
HttpResponseMessage response = await _httpClient.GetAsync(endpoint);
response.EnsureSuccessStatusCode(); // Throws if the status code is not 2xx
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
catch (HttpRequestException e)
{
// Handle exceptions (e.g., network errors, bad status codes)
Console.WriteLine($"Error fetching data: {e.Message}");
return null;
}
}
}
To use this service in your ViewModel or Page:
// In your Page or ViewModel
var apiService = new ApiService();
string data = await apiService.GetDataAsync("todos/1");
if (data != null)
{
// Process the received data (e.g., parse JSON and update UI)
Console.WriteLine(data);
}
Handling Responses
The HttpResponseMessage
object returned by HttpClient
methods contains important information about the response, including the status code, headers, and content.
response.IsSuccessStatusCode
: A boolean indicating if the HTTP status code was in the 2xx range.
response.StatusCode
: The HTTP status code (e.g., HttpStatusCode.OK
, HttpStatusCode.NotFound
).
response.Content.ReadAsStringAsync()
: Reads the response body as a string.
response.Content.ReadAsStreamAsync()
: Reads the response body as a stream.
POST, PUT, DELETE Requests
HttpClient
supports all standard HTTP methods. For example, to send data in a POST request:
using System.Text;
using System.Text.Json;
// ... inside ApiService class ...
public async Task<bool> PostDataAsync(string endpoint, object data)
{
try
{
string jsonContent = JsonSerializer.Serialize(data);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PostAsync(endpoint, content);
response.EnsureSuccessStatusCode();
return true; // Indicate success
}
catch (HttpRequestException e)
{
Console.WriteLine($"Error posting data: {e.Message}");
return false;
}
}
Best Practices
Important: HttpClient
is intended to be instantiated once and re-used for the lifetime of the application. Creating a new instance for every request can lead to socket exhaustion and performance issues. Dependency Injection is the recommended way to manage HttpClient
instances.
- Reuse HttpClient: As mentioned, instantiate
HttpClient
once.
- Configure BaseAddress: Set
BaseAddress
for common API endpoints.
- Set Timeouts: Configure default timeouts if needed.
- Handle Exceptions: Always wrap your network calls in
try-catch
blocks.
- Use Dependency Injection: Inject
HttpClient
via your application's DI container.
Further Reading
For more advanced scenarios, including request cancellation, custom headers, and complex authentication, refer to the official .NET documentation:
HttpClient Usage Guidelines
HttpClient in .NET MAUI (Official Doc)