| MAUI-SQLite-CRUD | MAUI-HttpClient-CRUD | |
.NET MAUI Networking with HttpClient |
In .NET MAUI, networking is primarily handled using the HttpClient class from the System.Net.Http namespace. It allows you to perform asynchronous CRUD (Create, Read, Update, Delete) operations against RESTful web services. Microsoft Learn Microsoft Learn +2
It is a best practice to instantiate HttpClient once and reuse it throughout the application's lifetime to avoid socket exhaustion. Microsoft Learn Microsoft Learn +4
Initialization: Declare it at the class level within a service class.
JSON Serialization: Use System.Text.Json to convert C# objects to JSON (serialization) and JSON back to C# objects (deserialization). Microsoft Learn Microsoft Learn +4
| Method | Purpose | Key HttpClient Call |
|---|---|---|
| GET | Retrieve data | GetAsync(url) or GetStringAsync(url) |
| POST | Create new data | PostAsync(url, content) |
| PUT | Update existing data | PutAsync(url, content) |
| DELETE | Remove data | DeleteAsync(url) |
Define a class that matches the JSON structure you expect from the API.
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
You can register HttpClient in MauiProgram.cs for dependency injection:
builder.Services.AddHttpClient();
Example: Fetch posts from a REST API.
using System.Net.Http.Json;
public class ApiService
{
private readonly HttpClient _httpClient;
public ApiService(HttpClient httpClient)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
}
public async Task<List<Post>> GetPostsAsync()
{
return await _httpClient.GetFromJsonAsync<List<Post>>("posts");
}
}
public async Task<Post> CreatePostAsync(Post newPost)
{
var response = await _httpClient.PostAsJsonAsync("posts", newPost);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<Post>();
}
public async Task<Post> UpdatePostAsync(Post updatedPost)
{
var response = await _httpClient.PutAsJsonAsync($"posts/{updatedPost.Id}", updatedPost);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<Post>();
}
public async Task DeletePostAsync(int id)
{
var response = await _httpClient.DeleteAsync($"posts/{id}");
response.EnsureSuccessStatusCode();
}
| MAUI-SQLite-CRUD | MAUI-HttpClient-CRUD | |