我正在尝试使用 DelegatingHandler 实现重试,但我也想设置 HttpCompletionOption。
我的代码如下所示:
public class RetryHandler : DelegatingHandler
{
private readonly int MaxRetries;
public RetryHandler(HttpMessageHandler innerHandler, int retryCount = 3)
: base(innerHandler)
{
MaxRetries = retryCount;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
for (var i = 0; i < MaxRetries; i++)
{
response = await base.SendAsync(request, cancellationToken);
if (response.IsSuccessStatusCode)
{
return response;
}
}
return response;
}
}
static void Main(string[] args)
{
using (var client = new HttpClient(new RetryHandler(new HttpClientHandler())))
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://ptsv2.com/t/smz9v-1564979884/post");
var myResult = client.SendAsync(request).Result;
Console.WriteLine(myResult.ToString());
}
Console.ReadLine();
}
正如您所看到的,没有通过继承 DelegatingHandler 来设置 HttpCompletionOption 的选项,我尝试创建 CustomDelegatinghandler,但在这种情况下,我无法像在 main 方法中使用的那样使用new RetryHandler(new HttpClientHandler()) 。
有没有办法实现具有/支持以下签名的 DelegatingHandler(或自定义)?
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, HttpCompletionOption option,
CancellationToken cancellationToken)
任何帮助,将不胜感激。谢谢,