Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/wordlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ circuitbreaker
comparer
contrib
deserialization
dependencyinjection
dotnet
dotnetrocks
durations
Expand All @@ -21,6 +22,8 @@ extensibility
flurl
fs
hangfire
httpclient
httpclientfactory
interop
jetbrains
jitter
Expand Down Expand Up @@ -50,6 +53,7 @@ rebase
rebased
rebasing
resharper
restsharp
rethrow
rethrows
retryable
Expand Down
5 changes: 4 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<ItemGroup>
<PackageVersion Include="coverlet.msbuild" Version="6.0.4" />
<PackageVersion Include="BenchmarkDotNet" Version="0.14.0" />
<PackageVersion Include="flurl.http.signed" Version="4.0.2" />
<PackageVersion Include="FSharp.Core" Version="8.0.200" />
<PackageVersion Include="GitHubActionsTestLogger" Version="2.4.1" />
<PackageVersion Include="IcedTasks" Version="0.11.4" />
Expand All @@ -37,7 +38,9 @@
<PackageVersion Include="Polly.Extensions" Version="$(PollyVersion)" />
<PackageVersion Include="Polly.Testing" Version="$(PollyVersion)" />
<PackageVersion Include="Polly.Contrib.WaitAndRetry" Version="1.1.1" />
<PackageVersion Include="refit.HttpClientFactory" Version="8.0.0" />
<PackageVersion Include="ReportGenerator" Version="5.4.5" />
<PackageVersion Include="Restsharp" Version="112.1.0" />
<PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="SonarAnalyzer.CSharp" Version="10.8.0.113526" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
Expand All @@ -49,4 +52,4 @@
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.0.2" />
</ItemGroup>
</Project>
</Project>
200 changes: 200 additions & 0 deletions docs/community/http-client-integrations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
# HTTP client integration samples

The transient failures are inevitable for HTTP based communication as well. It is not a surprise that many developers want to use Polly with some HTTP client.

Here we have collected some of the most commonly used HTTP client libraries and how to integrate them with Polly.

## Setting the stage

In the examples below we will register HTTP clients into a Dependency Injection container.

Each time the same resilience strategy will be used to keep the samples focused on the HTTP client library integration.

<!-- snippet: http-client-integrations-handle-transient-errors -->
```cs
private static ValueTask<bool> HandleTransientHttpError(Outcome<HttpResponseMessage> outcome)
=> outcome switch
{
{ Exception: HttpRequestException } => PredicateResult.True(),
{ Result.StatusCode: HttpStatusCode.RequestTimeout } => PredicateResult.True(),
{ Result.StatusCode: >= HttpStatusCode.InternalServerError } => PredicateResult.True(),
_ => PredicateResult.False()
};

private static RetryStrategyOptions<HttpResponseMessage> GetRetryOptions()
=> new()
{
ShouldHandle = args => HandleTransientHttpError(args.Outcome),
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
Delay = TimeSpan.FromSeconds(2)
};
```
<!-- endSnippet -->

Here we create a strategy which will retry the HTTP request if the status code is either 408 or greater than 500 or an `HttpRequestException` was thrown.

The `HandleTransientHttpError` is a V8 port of the [`HttpPolicyExtensions.HandleTransientHttpError`](https://github.com/App-vNext/Polly.Extensions.Http/tree/master).

## HttpClient based

We use the [`AddResilienceHandler`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.resiliencehttpclientbuilderextensions.addresiliencehandler) method to register our resilience strategy on the built-in [`HttpClient`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient).

<!-- snippet: http-client-integrations-httpclient -->
```cs
ServiceCollection services = new();

// Register a named HttpClient and decorate with a resilience pipeline
services.AddHttpClient(string.Empty)
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("httpclient_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

var provider = services.BuildServiceProvider();

// Resolve the named HttpClient
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient();

// Use the HttpClient by making a request
var response = await httpClient.GetAsync(new Uri("/408"));
```
<!-- endSnippet -->

> [!NOTE]
> The following packages are required to the above example:
>
> - [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/microsoft.extensions.dependencyinjection): Required for the dependency injection structures
> - [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/): Required for the `AddHttpClient` extension
> - [Microsoft.Extensions.Http.Resilience](https://www.nuget.org/packages/Microsoft.Extensions.Http.Resilience): Required for the `AddResilienceHandler` extension
### Further readings for HttpClient

- [Build resilient HTTP apps: Key development patterns](https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience)
- [Building resilient cloud services with .NET 8](https://devblogs.microsoft.com/dotnet/building-resilient-cloud-services-with-dotnet-8/)

## Flurl based

The named `HttpClient` registration and its decoration with our resilience strategy are the same as the built-in `HttpClient`.

Here we create a `FlurlClient` which uses the decorated, named `HttpClient` to perform HTTP communication.

<!-- snippet: http-client-integrations-flurl -->
```cs
ServiceCollection services = new();

// Register a named HttpClient and decorate with a resilience pipeline
services.AddHttpClient(string.Empty)
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("flurl_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

var provider = services.BuildServiceProvider();

// Resolve the named HttpClient and create a new FlurlClient
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var apiClient = new FlurlClient(httpClientFactory.CreateClient());

// Use the FlurlClient by making a request
var res = await apiClient.Request("/408").GetAsync();
```
<!-- endSnippet -->

> [!NOTE]
> The following packages are required to the above example:
>
> - [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/microsoft.extensions.dependencyinjection): Required for the dependency injection structures
> - [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/): Required for the `AddHttpClient` extension
> - [Microsoft.Extensions.Http.Resilience](https://www.nuget.org/packages/Microsoft.Extensions.Http.Resilience): Required for the `AddResilienceHandler` extension
> - [Flurl.Http](https://www.nuget.org/packages/Flurl.Http/): Required for the `FlurlClient`
### Further readings for Flurl

- [Flurl home page](https://flurl.dev/)

## Refit based

First let's define the API interface:

<!-- snippet: http-client-integrations-refit-interface -->
```cs
public interface IHttpStatusApi
{
[Get("/408")]
Task<HttpResponseMessage> GetRequestTimeoutEndpointAsync();
}
```
<!-- endSnippet -->

Then use the `AddRefitClient` to register the interface as typed HttpClient. Finally call `AddResilienceHandler` to decorate the underlying `HttpClient` with our resilience strategy.

<!-- snippet: http-client-integrations-refit -->
```cs
ServiceCollection services = new();

// Register a refit generated typed HttpClient and decorate with a resilience pipeline
services.AddRefitClient<IHttpStatusApi>()
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("refit_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

// Resolve the typed HttpClient
var provider = services.BuildServiceProvider();
var apiClient = provider.GetRequiredService<IHttpStatusApi>();

// Use the refit generated typed HttpClient by making a request
var response = await apiClient.GetRequestTimeoutEndpointAsync();
```
<!-- endSnippet -->

> [!NOTE]
> The following packages are required to the above example:
>
> - [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/microsoft.extensions.dependencyinjection): Required for the dependency injection structures
> - [Microsoft.Extensions.Http.Resilience](https://www.nuget.org/packages/Microsoft.Extensions.Http.Resilience): Required for the `AddResilienceHandler` extension
> - [Refit.HttpClientFactory](https://www.nuget.org/packages/Refit.HttpClientFactory): Required for the `AddRefitClient` extension
### Further readings for Refit

- [Using ASP.NET Core 2.1's HttpClientFactory with Refit's REST library](https://www.hanselman.com/blog/using-aspnet-core-21s-httpclientfactory-with-refits-rest-library)
- [Refit in .NET: Building Robust API Clients in C#](https://www.milanjovanovic.tech/blog/refit-in-dotnet-building-robust-api-clients-in-csharp)
- [Understand the Refit in .NET Core](https://medium.com/@jaimin_99136/understand-the-refit-in-net-core-ba0097c5e620)

## RestSharp based

The named `HttpClient` registration and its decoration with our resilience strategy are the same as the built-in `HttpClient`.

Here we create a `RestClient` which uses the decorated, named `HttpClient` to perform HTTP communication.

<!-- snippet: http-client-integrations-restsharp -->
```cs
ServiceCollection services = new();

// Register a named HttpClient and decorate with a resilience pipeline
services.AddHttpClient(string.Empty)
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("restsharp_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

var provider = services.BuildServiceProvider();

// Resolve the named HttpClient and create a RestClient
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var restClient = new RestClient(httpClientFactory.CreateClient());

// Use the RestClient by making a request
var request = new RestRequest("/408", Method.Get);
var response = await restClient.ExecuteAsync(request);
```
<!-- endSnippet -->

> [!NOTE]
> The following packages are required to the above example:
>
> - [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/microsoft.extensions.dependencyinjection): Required for the dependency injection structures
> - [Microsoft.Extensions.Http.Resilience](https://www.nuget.org/packages/Microsoft.Extensions.Http.Resilience): Required for the `AddResilienceHandler` extension
> - [RestSharp](https://www.nuget.org/packages/RestSharp): Required for the `RestClient`, `RestRequest`, `RestResponse`, etc. structures
### Further readings for RestSharp

- [RestSharp home page](https://restsharp.dev/)
2 changes: 2 additions & 0 deletions docs/community/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@
href: git-workflow.md
- name: Cheat sheets
href: cheat-sheets.md
- name: HTTP client integration samples
href: http-client-integrations.md
129 changes: 129 additions & 0 deletions src/Snippets/Docs/HttpClientIntegrations.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
using System.Net;
using System.Net.Http;
using Flurl.Http;
using Microsoft.Extensions.DependencyInjection;
using Polly.Retry;
using Refit;
using RestSharp;

namespace Snippets.Docs;

internal static class HttpClientIntegrations
{
private static readonly Uri DownstreamUri = new("https://httpstat.us/408");

#region http-client-integrations-handle-transient-errors
private static ValueTask<bool> HandleTransientHttpError(Outcome<HttpResponseMessage> outcome)
=> outcome switch
{
{ Exception: HttpRequestException } => PredicateResult.True(),
{ Result.StatusCode: HttpStatusCode.RequestTimeout } => PredicateResult.True(),
{ Result.StatusCode: >= HttpStatusCode.InternalServerError } => PredicateResult.True(),
_ => PredicateResult.False()
};

private static RetryStrategyOptions<HttpResponseMessage> GetRetryOptions()
=> new()
{
ShouldHandle = args => HandleTransientHttpError(args.Outcome),
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
Delay = TimeSpan.FromSeconds(2)
};
#endregion

public static async Task HttpClientExample()
{
#region http-client-integrations-httpclient
ServiceCollection services = new();

// Register a named HttpClient and decorate with a resilience pipeline
services.AddHttpClient(string.Empty)
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("httpclient_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

var provider = services.BuildServiceProvider();

// Resolve the named HttpClient
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient();

// Use the HttpClient by making a request
var response = await httpClient.GetAsync(new Uri("/408"));
#endregion
}

public static async Task RefitExample()
{
#region http-client-integrations-refit
ServiceCollection services = new();

// Register a refit generated typed HttpClient and decorate with a resilience pipeline
services.AddRefitClient<IHttpStatusApi>()
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("refit_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

// Resolve the typed HttpClient
var provider = services.BuildServiceProvider();
var apiClient = provider.GetRequiredService<IHttpStatusApi>();

// Use the refit generated typed HttpClient by making a request
var response = await apiClient.GetRequestTimeoutEndpointAsync();
#endregion
}

public static async Task FlurlExample()
{
#region http-client-integrations-flurl
ServiceCollection services = new();

// Register a named HttpClient and decorate with a resilience pipeline
services.AddHttpClient(string.Empty)
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("flurl_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

var provider = services.BuildServiceProvider();

// Resolve the named HttpClient and create a new FlurlClient
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var apiClient = new FlurlClient(httpClientFactory.CreateClient());

// Use the FlurlClient by making a request
var res = await apiClient.Request("/408").GetAsync();
#endregion
}

public static async Task RestSharpExample()
{
#region http-client-integrations-restsharp
ServiceCollection services = new();

// Register a named HttpClient and decorate with a resilience pipeline
services.AddHttpClient(string.Empty)
.ConfigureHttpClient(client => client.BaseAddress = DownstreamUri)
.AddResilienceHandler("restsharp_based_pipeline",
builder => builder.AddRetry(GetRetryOptions()));

var provider = services.BuildServiceProvider();

// Resolve the named HttpClient and create a RestClient
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var restClient = new RestClient(httpClientFactory.CreateClient());

// Use the RestClient by making a request
var request = new RestRequest("/408", Method.Get);
var response = await restClient.ExecuteAsync(request);
#endregion
}
}

#region http-client-integrations-refit-interface
public interface IHttpStatusApi
{
[Get("/408")]
Task<HttpResponseMessage> GetRequestTimeoutEndpointAsync();
}
#endregion
3 changes: 3 additions & 0 deletions src/Snippets/Snippets.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="flurl.http.signed" />
<PackageReference Include="refit.HttpClientFactory" />
<PackageReference Include="Restsharp" />
<ProjectReference Include="..\Polly.Extensions\Polly.Extensions.csproj" />
<ProjectReference Include="..\Polly.RateLimiting\Polly.RateLimiting.csproj" />
<ProjectReference Include="..\Polly.Testing\Polly.Testing.csproj" />
Expand Down