Polly with .NET 6, Part 6 - Policy Wraps with Minimal APIs

Want to learn more about Polly? Check out my Pluralsight course on it.

A reader of the blog wrote asking me about using Polly Policy Wraps with Minimal APIs in .NET. It is something I’ve written about in the past, but my examples used traditional controllers.

Here is how to use them with API Endpoints.

First, add the Microsoft.Extensions.Http.Polly package to your project. That will bring in all the other dependencies you need.

See below for a explanation of the code.

 1using System.Net;
 2using Polly;
 3using Polly.Extensions.Http;
 4
 5var builder = WebApplication.CreateBuilder(args);
 6
 7IAsyncPolicy<HttpResponseMessage> httpRetryPolicy = HttpPolicyExtensions
 8    .HandleTransientHttpError()
 9    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));
10    
11IAsyncPolicy<HttpResponseMessage> httpRequestFallbackPolicy = 
12    HttpPolicyExtensions.HandleTransientHttpError()
13    .FallbackAsync(new HttpResponseMessage(HttpStatusCode.OK)
14    {
15        Content = new StringContent("-1")
16    });
17
18IAsyncPolicy<HttpResponseMessage> retryAndFallbackWrap = 
19    Policy.WrapAsync(httpRequestFallbackPolicy, httpRetryPolicy);
20
21builder.Services.AddSingleton(retryAndFallbackWrap);
22
23var app = builder.Build();
24
25int requestCount = 0;
26
27// Endpoint that fails 100% of the time
28app.MapGet("/Inventory/{id}", (int id) =>
29{
30    Console.WriteLine($"{++requestCount} Something went wrong");
31    return Results.Problem("Something went wrong");
32});
33
34
35HttpClient httpClient = new HttpClient()
36{
37    BaseAddress = new Uri("http://localhost:5000")
38};
39
40// Endpoint that takes a Polly Policy by DI
41app.MapGet("/Catalog/{id}", async (int id, IAsyncPolicy<HttpResponseMessage> policy) =>
42{
43    string requestEndpoint = $"Inventory/{id}";
44
45    HttpResponseMessage response = await policy.ExecuteAsync(() =>
46    httpClient.GetAsync(requestEndpoint));
47
48    if (response.IsSuccessStatusCode)
49    {
50        int itemsInStock = await response.Content.ReadFromJsonAsync<int>();
51        return Results.Ok(itemsInStock);
52    }
53    return Results.Problem("Something went calling the inventory");
54});
55
56app.Run();
  • Lines 7-9 create a Wait and Retry Policy that retries up to three times.
  • Lines 11-16 create the Fallback Policy that returns an OK HttpResponseMessage with a content of “-1”.
  • Lines 18-19 create the Policy Wrap that wraps the Fallback Policy around the Wait and Retry Policy.
  • Line 21 adds the Policy Wrap to the service collection.
  • Lines 28-32 create an endpoint that fails 100% of the time.
  • Lines 41-54 create an endpoint that takes Policy Wrap as a parameter and uses it to wrap the HttpClient call to the failing endpoint.

In the next post I’ll show how to do the same with a HttpClientFactory.

comments powered by Disqus

Related