Gå till huvudinnehållet Gå till huvudmenyn

Building robust HTTP clients in .NET

Av Emil Ekman Lästid: 1 minut

HTTP clients are the backbone of modern applications, enabling communication with external APIs and services. However, not all HTTP client implementations are created equal. In this post, we'll explore how to evolve from a basic HTTP client to a sophisticated, production-ready implementation with proper authentication, error handling, and maintainability. We will use a real-world example of a Customer Management API (CMA) service client to demonstrate each evolution step, showing how each improvement adds value and addresses specific challenges. In the real world I would recommend naming the client by a descriptive name, CustomerManagementHttpClient, but to save horizontal space in this blog post, we'll simply refer to it as CmaHttpClient.

kollage

Stage 1: HttpClient, as simple as it gets.

Let's start with the bare minimum. You want data, and you're going to get it. 

Implementation

 

public class CmaHttpClient(HttpClient httpClient)
{
    public Task<List<Customer>> ListCustomers() => httpClient.GetFromJsonAsync<List<Customer>>();
}

Registration

It's generally a good idea to fetch your base address from configuration, but for the sake of simplicity, we'll hard-code it.

 

services.AddHttpClient<CmaClient>(client =>
{
    client.BaseAddress = new Uri("https://cma.com/api");
});

Stage 2: Abstracting your client

If you intend to test code that depends on your client, or you plan to ship your client as part of a reusable module, it is beneficial to abstract it, allowing your abstraction to be mocked. If your app is tiny with low growth expectancy, and you do not plan to write tests for it, I'd say it's better to keep it simple and skip the abstraction.

Vi vill gärna höra vad du tycker om inlägget

Emil Ekman

Emil Ekman

Head of engineering

Läs alla blogginlägg av Emil Ekman