I have a console application that uses HttpClient to make web requests.
var client = new HttpClient();
I'm trying to add multiple HttpMessageHandler to it (custom implementations of DelegatingHandler, really) but the constructor for HttpClient only takes a single HttpMessageHandler.
class LoggingHandler : DelegatingHandler { //... }
class ResponseContentProcessingHandler : DelegatingHandler { //... }
this is ok...
var client = new HttpClient(new LoggingHandler()); // OK
but this doesn't compile:
var client = new HttpClient(
new LoggingHandler(),
new ResponseContentProcessingHandler()); // Sadness
Because I'm targeting .NET 4.0, I cannot use HttpClientFactory, which is how the solution to this problem is commonly explained:
HttpClient client = HttpClientFactory.Create(
new LoggingHandler(),
new ResponseContentProcessingHandler());
Because I'm just in a console application, rather than in an ASP.NET application, I can't do this either:
GlobalConfiguration.Configuration
.MessageHandlers
.Add(new LoggingHandler()
.Add(new ResponseContentProcessingHandler());
I've looked at the source for HttpClientFactory and there doesn't seem to be anything in there that wouldn't compile in .NET 4.0, but short of rolling my own factory ("inspired" by Microsoft's source code), is there a way to manually add many HTTP message handlers to the HttpClient?
I think you can just do something like this:
var loggingHandler = new LoggingHandler();
var responseContentProcessingHandler = new ResponseContentProcessingHandler();
loggingHandler.InnerHandler = responseContentProcessingHandler;
var client = new HttpClient(loggingHandler);
So that you don't need to create a CustomHandler just for the chaining purpose. That's really the purpose of DelegatingHandler.