Previous MAUI-SQLite-CRUD MAUI-HttpClient-CRUD Next

.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

1. Setting Up HttpClient

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

2. Common HTTP Operations

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)

3. Implementation Workflow

  • Define Models: Create C# classes that match the structure of the JSON data you expect to receive.
  • Create an API Service: Encapsulate your networking logic in a dedicated class (e.g., ApiService) to keep your code clean and testable.
  • Handle Responses: Check response.IsSuccessStatusCode to ensure the request was successful before processing the content.

Platform Considerations:

  • Connectivity: Use the IConnectivity interface in the Microsoft.Maui.Networking namespace to check for an active internet connection before making calls.
  • Local Services: When debugging against a local web API (e.g., localhost), you must enable clear-text HTTP traffic for Android and iOS. Microsoft Learn Microsoft Learn +6

4. Advanced Networking Tools

  • IHttpClientFactory: For complex apps, use IHttpClientFactory to manage the lifetime of your handlers and prevent DNS issues.
  • Refit: A popular library that allows you to define REST interfaces and generates the boilerplate code for you automatically. Microsoft Learn Microsoft Learn +3

Would you like to see a specific code example for any of these?

  • A basic GET request with JSON deserialization
  • A POST request sending a user object to an API
  • How to configure IHttpClientFactory for dependency injection
  • How to handle HTTPS/SSL certificates during local development

.NET MAUI HttpClient Step-by-Step Guide

🌐 Why HttpClient?

  • Built into .NET, lightweight, and flexible.
  • Handles GET, POST, PUT, DELETE requests.
  • Supports async programming, which is essential for mobile apps.

🧩 Step-by-Step Guide

1. Create a Model

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; }
}

2. Setup HttpClient

You can register HttpClient in MauiProgram.cs for dependency injection:

builder.Services.AddHttpClient();

3. Consuming an API (GET)

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");
    }
}

4. Sending Data (POST)

public async Task<Post> CreatePostAsync(Post newPost)
{
    var response = await _httpClient.PostAsJsonAsync("posts", newPost);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadFromJsonAsync<Post>();
}

5. Updating Data (PUT)

public async Task<Post> UpdatePostAsync(Post updatedPost)
{
    var response = await _httpClient.PutAsJsonAsync($"posts/{updatedPost.Id}", updatedPost);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadFromJsonAsync<Post>();
}

6. Deleting Data (DELETE)

public async Task DeletePostAsync(int id)
{
    var response = await _httpClient.DeleteAsync($"posts/{id}");
    response.EnsureSuccessStatusCode();
}

✅ Checklist Recap

  • Create model classes to match JSON.
  • Register HttpClient in MauiProgram.cs.
  • Use GetFromJsonAsync for GET requests.
  • Use PostAsJsonAsync for POST.
  • Use PutAsJsonAsync for PUT.
  • Use DeleteAsync for DELETE.
Back to Index
Previous MAUI-SQLite-CRUD MAUI-HttpClient-CRUD Next
*