-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[DOCS] Add HTTP client integration samples #2587
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
martincostello
merged 5 commits into
App-vNext:main
from
peter-csala:2530-Add-http-client-samples
Apr 17, 2025
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d548d65
Add HTTP client integration samples
peter-csala 742a57b
Apply suggestions from code review
peter-csala 531ed8f
Apply review suggestions
peter-csala f361af6
Apply review suggestions
peter-csala 5695a95
Fix linting issue
peter-csala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Here we have collected some of the most commonly used HTTP client libraries and how to integrate them with Polly. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ## 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. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| <!-- 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. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| The `HandleTransientHttpError` is a V8 port of the [`HttpPolicyExtensions.HandleTransientHttpError`](https://github.com/App-vNext/Polly.Extensions.Http/tree/master). | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ## HttpClient based | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| 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). | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| <!-- 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 | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/): Required for the `AddHttpClient` extension | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [Microsoft.Extensions.Http.Resilience](https://www.nuget.org/packages/Microsoft.Extensions.Http.Resilience): Required for the `AddResilienceHandler` extension | ||
| ### Further readings for HttpClient | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| - [Build resilient HTTP apps: Key development patterns](https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience) | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| - [Building resilient cloud services with .NET 8](https://devblogs.microsoft.com/dotnet/building-resilient-cloud-services-with-dotnet-8/) | ||
|
|
||
| ## Flurl based | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| The named `HttpClient` registration and its decoration with our resilience strategy are the same as the built-in `HttpClient`. | ||
peter-csala marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| Here we create a `FlurlClient` which uses the decorated, named `HttpClient` to perform HTTP communication. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| <!-- 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 | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/): Required for the `AddHttpClient` extension | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [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 | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| - [Flurl home page](https://flurl.dev/) | ||
|
|
||
| ## Refit based | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| First let's define the API interface: | ||
peter-csala marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| <!-- 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. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| <!-- 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 | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [Microsoft.Extensions.Http.Resilience](https://www.nuget.org/packages/Microsoft.Extensions.Http.Resilience): Required for the `AddResilienceHandler` extension | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [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) | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ## RestSharp based | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| The named `HttpClient` registration and its decoration with our resilience strategy are the same as the built-in `HttpClient`. | ||
peter-csala marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| Here we create a `RestClient` which uses the decorated, named `HttpClient` to perform HTTP communication. | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| <!-- 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 | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > - [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 | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ### Further readings for RestSharp | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| - [RestSharp home page](https://restsharp.dev/) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| #region http-client-integrations-handle-transient-errors | ||
| private static ValueTask<bool> HandleTransientHttpError(Outcome<HttpResponseMessage> outcome) | ||
| => outcome switch | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| { Exception: HttpRequestException } => PredicateResult.True(), | ||
| { Result.StatusCode: HttpStatusCode.RequestTimeout } => PredicateResult.True(), | ||
| { Result.StatusCode: >= HttpStatusCode.InternalServerError } => PredicateResult.True(), | ||
| _ => PredicateResult.False() | ||
| }; | ||
|
|
||
| private static RetryStrategyOptions<HttpResponseMessage> GetRetryOptions() | ||
| => new() | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| 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(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // 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(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Resolve the named HttpClient | ||
peter-csala marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>(); | ||
| var httpClient = httpClientFactory.CreateClient(); | ||
|
|
||
| // Use the HttpClient by making a request | ||
| var response = await httpClient.GetAsync(new Uri("/408")); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| #endregion | ||
| } | ||
|
|
||
| public static async Task RefitExample() | ||
| { | ||
| #region http-client-integrations-refit | ||
| ServiceCollection services = new(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Register a refit generated typed HttpClient and decorate with a resilience pipeline | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| services.AddRefitClient<IHttpStatusApi>() | ||
| .ConfigureHttpClient(client => client.BaseAddress = DownstreamUri) | ||
| .AddResilienceHandler("refit_based_pipeline", | ||
| builder => builder.AddRetry(GetRetryOptions())); | ||
|
|
||
| // Resolve the typed HttpClient | ||
| var provider = services.BuildServiceProvider(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var apiClient = provider.GetRequiredService<IHttpStatusApi>(); | ||
|
|
||
| // Use the refit generated typed HttpClient by making a request | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var response = await apiClient.GetRequestTimeoutEndpointAsync(); | ||
| #endregion | ||
| } | ||
|
|
||
| public static async Task FlurlExample() | ||
| { | ||
| #region http-client-integrations-flurl | ||
| ServiceCollection services = new(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Register a named HttpClient and decorate with a resilience pipeline | ||
| services.AddHttpClient(string.Empty) | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| .ConfigureHttpClient(client => client.BaseAddress = DownstreamUri) | ||
| .AddResilienceHandler("flurl_based_pipeline", | ||
| builder => builder.AddRetry(GetRetryOptions())); | ||
|
|
||
| var provider = services.BuildServiceProvider(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // 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(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| #endregion | ||
| } | ||
|
|
||
| public static async Task RestSharpExample() | ||
| { | ||
| #region http-client-integrations-restsharp | ||
| ServiceCollection services = new(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Register a named HttpClient and decorate with a resilience pipeline | ||
| services.AddHttpClient(string.Empty) | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| .ConfigureHttpClient(client => client.BaseAddress = DownstreamUri) | ||
| .AddResilienceHandler("restsharp_based_pipeline", | ||
| builder => builder.AddRetry(GetRetryOptions())); | ||
|
|
||
| var provider = services.BuildServiceProvider(); | ||
peter-csala marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.