/// <summary>
/// 重试
/// </summary>
public class RetryHandler : DelegatingHandler
{
private const int maxRetries = 3;
/// <summary>
/// 重试
/// </summary>
/// <param name="innerHandler"></param>
public RetryHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{ }
/// <summary>
/// 重试
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
for (int i = 0; i < maxRetries; i++)
{
response = await base.SendAsync(request, cancellationToken);
if (response.IsSuccessStatusCode)
{
return response;
}
}
return response;
}
}
使用:
var client = new HttpClient(new RetryHandler(new HttpClientHandler())