In the code snippet below I am trying to implement a DelegatingHandler. You will notice that in the SendAsync method I am deviating from the conventional practice of passing the request to the InnerHandler...
base.SendAsync(request, cancellationToken);
...and instead am creating a new instance of HttpClient, to which I am passing the request:
new HttpClient().SendAsync(request, cancellationToken);
This may seem strange in a bare bone snippet like this one, but the idea here is to pass the request to different HttpClientHandlers depending on certain conditions, so I will need to be able to instantiate the HttpClient dynamically.
However, when I run this code I receive the following exception:
The request message was already sent. Cannot send the same request message multiple times.
Can someone please help me understand what causes it and what would be a better way to implement my requirement (short of cloning the request in the handler rather than passing it on, which works, but doesn't appear elegant)?
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DelegatingHandlerTest
{
internal static class Program
{
private static void Main()
{
var httpClient = new HttpClient(new MyTestHandler());
var response = httpClient.GetAsync("http://icanhazip.com/").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
private class MyTestHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return await new HttpClient().SendAsync(request, cancellationToken);
}
}
}