Ejemplo n.º 1
0
        /// <summary>
        /// This policy will be added and configured in Startup.cs or where you add your http clients to services. It will retry the http call as many times as it is configured.
        /// </summary>
        /// <param name="builder">The http client builder parameter. This is actually the AddHttpClient<>().</param>
        /// <param name="onRetryAsyncFunc">This represents the delegate with the parameters obtained after each call. It can be used when it is configured in order to add you custom logic after the http call is done (log, do something else).</param>
        /// <param name="retryAttempts">Represents the number of retries of your http call.</param>
        /// <param name="httpStatusCodeToRetry">Represents a list of http status codes. You can add you own logic here (for which http codes the retry should happen). Be aware that default behaviour is to not retry an http call if the result code belongs to 2xx http status codes.</param>
        /// <param name="onResultFunc">Represent a custom action which can be condigured at startup in order to execeute that specific action on the received http response message.</param>
        /// <param name="sleepDuration">Represent the number of seconds used to wait between http calls retries.</param>
        /// <param name="timeoutDurationPerPolicyRequest">Represent the number of seconds used to wait for each policy retry request. The exception thrown in case the request will overlap the value is  <see cref="T:Polly.Timeout.TimeoutRejectedException" />. In case this property is not set (null) then no timeout policy will be added to this http client.</param>
        /// <returns>The policy handlers with all the configurable rules.</returns>
        public static IHttpClientBuilder ConfigureRetryPolicy(
              this IHttpClientBuilder builder,
              Func<DelegateResult<HttpResponseMessage>, TimeSpan, int, Context, Task> onRetryAsyncFunc = null,
              int retryAttempts = 3,
              IEnumerable<HttpStatusCode> httpStatusCodeToRetry = null,
              Func<HttpResponseMessage, Task<bool>> onResultFuncAsync = null,
              TimeSpan? sleepDuration = null,
              TimeSpan? timeoutDurationPerPolicyRequest = null)
        {
            var concreteTimeoutDurationPerPolicyRequest = GetConcreteTimeoutPerPolicyRequest(timeoutDurationPerPolicyRequest);

            var timeOutPolicy = BuildTimeoutPolicy(concreteTimeoutDurationPerPolicyRequest);
            var retryPolicy = BuildRetryPolicy(retryAttempts, onRetryAsyncFunc, httpStatusCodeToRetry, onResultFuncAsync, sleepDuration);

            builder.AddPolicyHandler(retryPolicy);
            builder.AddPolicyHandler(timeOutPolicy);

            builder.ChangeHttpClientTimoutValue(retryAttempts, concreteTimeoutDurationPerPolicyRequest, sleepDuration);

            return builder;
        }