Problem with inheriting DelegatingHandler.
Hello,
Sorry but I didn't know where and whom to ask about this?
I'm trying to implement HTTPClient's request retry using DelegatingHandler but I also want to set HttpCompletionOption.
My code looks like following :
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, HttpCompletionOption.ResponseHeadersRead).Result;
Console.WriteLine(myResult.ToString());
}
Console.ReadLine();
}
As you can see there is no option to set HttpCompletionOption by inheriting DelegatingHandler, I tried creating CustomDelegatinghandler but in that case I'm unable to use new RetryHandler(new HttpClientHandler()) as I have used in the main method.
- Is this by design?
- Is there any way to implement DelegatingHandlerthat supports following signature?
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, HttpCompletionOption option,
CancellationToken cancellationToken)
- Is there any way to customize DelegatingHandler and HttpMessageHandler to support above?
Any help would be appreciated. Thanks.
HttpCompletionOption is implemented entirely at the HttpClient level, with HttpClient layering that functionality on to of handlers. Handlers always implement the equivalent of ResponseHeadersRead, and then if the caller passed ResponseContentRead, HttpClient handles implementing that functionality by buffering the response stream returned by the handler.
Closing as by-design.