如何重试 401 请求以及 TransientHttpError(5XX 和 408)
how to re-try request for 401 along with TransientHttpError ( 5XX and 408)
当我们遇到来自 HttpRequestException、5XX 和 408 的错误并且它工作正常时,下面的代码重试 2 次。
这里偶401
错误我要重试?我们如何使用 Polly 实现这一目标?
services.AddHttpClient(Options.DefaultName)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
.AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
将 .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
添加到您的代码中:
services.AddHttpClient(Options.DefaultName)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
.AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
.OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
我建议像这样重写您的代码以使其更易于阅读:
services.AddHttpClient(Options.DefaultName)
.AddTransientHttpErrorPolicy(builder =>
builder
.OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
);
当我们遇到来自 HttpRequestException、5XX 和 408 的错误并且它工作正常时,下面的代码重试 2 次。
这里偶401
错误我要重试?我们如何使用 Polly 实现这一目标?
services.AddHttpClient(Options.DefaultName)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
.AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
将 .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
添加到您的代码中:
services.AddHttpClient(Options.DefaultName)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
.AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
.OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
我建议像这样重写您的代码以使其更易于阅读:
services.AddHttpClient(Options.DefaultName)
.AddTransientHttpErrorPolicy(builder =>
builder
.OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
);