I have implemented the below Polly Policies for the HttpClient.
IHostBuilder hostBuilder = new HostBuilder().ConfigureServices((hostContext, services) =>
{
AppSettings appSettings = new AppSettings();
IConfigurationRoot configuration = GetConfiguration();
configuration.Bind("Configuration", appSettings);
services.AddSingleton(appSettings); services.AddHttpClient("WebAPI", client =>
{
client.BaseAddress = new Uri(appSettings.WebApiBaseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
})
.AddPolicyHandler(HttpClientPolicyHandler.WaitAndRetry(appSettings.RetryCount))
.AddPolicyHandler(HttpClientPolicyHandler.Timeout(appSettings.TimeOut));
services.AddHostedService<RDPersister>();
});
await hostBuilder.RunConsoleAsync();
public static class HttpClientPolicyHandler
{
/// <summary>
/// Create a Wait and Retry policy for HttpClient on the basis of specified Status Code and Timeout.
/// </summary>
/// <param name="retryCount">Number of retries.</param>
/// <returns>Wait and Retry policy handler.</returns>
public static IAsyncPolicy<HttpResponseMessage> WaitAndRetry(int retryCount)
{
return HttpPolicyExtensions.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound)
.Or<TimeoutRejectedException>()
.Or<HttpRequestException>()
.WaitAndRetryAsync(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
/// <summary>
/// Create a Timeout policy for HttpClient.
/// </summary>
/// <param name="seconds">Timeout.</param>
/// <returns>Timeout policy handler.</returns>
public static IAsyncPolicy<HttpResponseMessage> Timeout(int seconds)
{
return Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(seconds));
}
}
Below is the asynchronous call of the web api
private async void CallWebApi(string webApiJsonMessage)
{
try
{
HttpClient client = _httpClientFactory.CreateClient("WebAPI");
string uri = "api/CalculateOrder";
HttpResponseMessage response = await client.PostAsync(uri, new StringContent(webApiJsonMessage, Encoding.UTF8, "application/json"));
string token = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
}
else
{
}
}
catch (Exception ex)
{
_logger.Error($"Exception occurred while calling WebAPI: {ex.Message} for message : {webApiJsonMessage}");
}
}
But I want to create a synchronous call to WebAPI since I want to wait for the response to come. My question then in that case do I need to create sync policy in Polly and how??
And one more question the timeout policy will work for the entire retries. Do I need to create one more policy for single retry timeout as well?
Any help??