Implementing Resilience in a .NET 8 Web API

In modern web development, building resilient APIs is crucial for ensuring reliability and performance. This blog will guide you through implementing resilience in a .NET 8 Web API using Microsoft.Extensions.Http.Resilience library. We'll cover setting up retry policies, and timeouts to make your API more robust against transient faults.

The source code can be downloaded from GitHub.

Step 1. Create a new .NET 8 Web API project

First, if you don't have an existing project, create one using the .NET CLI or use the default web API template.

Step 2. Add Required NuGet packages

Next, install the Microsoft.Extensions.Http.Resilience library via NuGet:

dotnet add package Microsoft.Extensions.Http.Resilience --version 8.0.0

Step 3. Configure Resilience in Program.cs

Modify the Program.cs file to set up HttpClient with resilience policies provided by Microsoft.Extensions.Http.Resilience. Here, we will define retry policies and timeouts.

//Add resilience pipeline
builder.Services.AddResiliencePipeline("default", x =>
{
    x.AddRetry(new Polly.Retry.RetryStrategyOptions
    {
        ShouldHandle = new PredicateBuilder().Handle<Exception>(),
        Delay = TimeSpan.FromSeconds(2),
        MaxRetryAttempts = 2,
        BackoffType = DelayBackoffType.Exponential,
        UseJitter = true
    })
    .AddTimeout(TimeSpan.FromSeconds(30));
});

Step 4. Use the Resilient HttpClient in a Service

Next, we'll inject and use the configured HttpClient in your Service. This example shows how to fetch data from an external API using the resilient HttpClient.

public class WeatherService
{
    private readonly HttpClient _httpClient;
    private readonly ResiliencePipelineProvider<string> _resiliencePipelineProvider;
    public WeatherService(HttpClient httpClient,
                         ResiliencePipelineProvider<string> resiliencePipelineProvider)
    {
        _httpClient = httpClient;
        _resiliencePipelineProvider = resiliencePipelineProvider;
           
    }
    public async Task<string> GetWeatherAsync()
    {
        var pipeline = _resiliencePipelineProvider.GetPipeline("default");
        var response = await pipeline
            .ExecuteAsync( async ct=> await _httpClient.GetAsync($"https://localhost:7187/weatherforecast",ct));
           
        return await response.Content.ReadAsStringAsync();
    }

}

Step 5. Add the endpoint in the Program.cs

app.MapGet("/weatherService/weather", async (WeatherService weatherService) =>
{
    var result = await weatherService.GetWeatherAsync();
    return result;
})
    .WithName("GetWeather")
    .WithOpenApi();

Step 6. Run the Application

Finally, run your application and navigate to the endpoint to see the resilient HttpClient in action.

References

Please refer to the below links for more details.

Conclusion

By following these steps, you have integrated resilience into your .NET 8 Web API project using Microsoft.Extensions.Http.Resilience library. The retry policies, circuit breaker settings, and timeouts will help ensure your API is robust against transient faults, improving its reliability and user experience.

Next Recommended Reading Implement Repository Pattern In .NET