使用DelegatingHandler实现HTTP请求重试逻辑

Using DelegatingHandler to implement HTTP request retry logic

我正在尝试使用 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 但在那种情况下我无法使用 new RetryHandler(new HttpClientHandler()) 正如我在主要方法中使用的那样。

是否有任何方法可以实现具有/支持以下签名的 DelegatingHandler(或自定义)?

protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, HttpCompletionOption option,
        CancellationToken cancellationToken)

如有任何帮助,我们将不胜感激。 谢谢,

您不需要包括 HttpCompletionOption in the message handler signature, because handling HttpCompletionOption is responsibility of HttpClient,而不是 HttpMessageHandler

一个HttpMessageHandler必须尽早发起一个发送请求的任务,return一个Task<HttpResponseMessage>。通常,它不应该对响应内容执行任何缓冲(好吧,除非它是为缓冲目的而创建的中间件),这就是它不接收 HttpCompletionOption 的原因。它应该始终表现得好像它已通过 HttpCompletionOption.ResponseHeadersRead

指定 HttpCompletionOption 的预期方法是将其包含在对 HttpClient 方法重载的调用中,例如 GetAsync or SendAsync:

client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

粗略地说,HttpClient 处理 HttpCompletionOption 如下:

  1. 调用消息处理程序并获得 Task<HttpResponseMessage> (see code)
  2. 如果指定了HttpCompletionOption.ResponseHeadersRead,则完成:return任务给调用者(see code
  3. 如果指定 HttpCompletionOption.ResponseContentRead,则 return 任务 HttpContent.LoadIntoBufferAsync,作为原始 Task<HttpResponseMessage> (see code)