![clock](../themes/indigo/img/timeicon.gif)
July 2, 2024 08:16 by
Peter
Creating robust APIs is more important than ever in the age of modern web development, especially with all these third-party integration we rely on. In this Blog, We will be guiding you how to introduce resilience in. Create an HTTP Client in a. Extensions. Http. Resilience library. In this section, we will take a look at features like setting up retry policies with exponential backoff and timeouts to make your API more resilient against the transient faults.
![](http://aspnetmvceuropeanhosting.hostforlife.eu/image.axd?picture=2015%2f10%2fhfl-new-banner.png)
Step 1. Create a new. NET 8 Web API project Step First, if you have no existing Project then create new with. NET CLI dotnet new web or starting with the default Web API template.
Step 2. Install the Microsoft.AspNetCore. 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.
- Building resilient cloud services with .NET 8
- Learning from Microsoft
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.