This small WebAPI is an example of using Refit, an automatic type-safe REST library. This concept can be beneficial for initiating calls to 3rd-party services.
- Refit 👤Official
- Refitter 👤Christian Helle - Generate the Refit interface from OpenAPI specifications
- Logging HTTP Traffic 📓NimblePros - Using HttpMessageHandler
- Bearer Authentication 📓NimblePros
- With Refit, you can use Polly as a resilience and transient-fault-handling library, which can helps you to easily write retry logic.
- Using Polly with HttpClient factory 👤
- In the example, I use a timeout policy to cancel a long-running call. You can find a solution for using
CancellationToken
in case the client-side application cancels the request.
- Popular library: RestSharp | RestSharp examples 📓Jason Watmore
- DalSoft.RestClient 📓CodeMaze - Dynamic and fluent C# rest client library
In my Playing with HttpClientFactory, I used the built-in
HttpClientFactory
to initiate http calls.
public void ConfigureServices(IServiceCollection services)
{
// Add: MessageHandler(s) to the DI container.
services.AddTransient<AuthorizationMessageHandler>();
// --> Create: Polly policy.
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>() // Thrown by Polly's TimeoutPolicy if the inner call gets timeout.
.WaitAndRetryAsync(wrc.Retry, _ => TimeSpan.FromMilliseconds(wrc.Wait));
AsyncTimeoutPolicy<HttpResponseMessage> timeoutPolicy = Policy
.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromMilliseconds(wrc.Timeout));
// -- Add: RefitClient.
services.AddRefitClient<IUserClient>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri("http://localhost:5000"))
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(timeoutPolicy) // The order of adding is imporant!
.AddHttpMessageHandler<AuthorizationMessageHandler>();
}