Reputation: 10932
I need to query against a Web API that sends responses which can be encrypted and/or compressed and/or Base64 encoded and I'd like to implement this as a chain of HttpMessageHandler
s very much like outlined in this post, which is for Web API though.
There is a constructor for HttpClient
taking an HttpMessageHandler
, so that is a start. Do I have to come up with a solution for chaining multiple handlers myself or is there maybe a better option?
Upvotes: 6
Views: 2888
Reputation: 39309
The easiest way to chain HttpMessageHandler
s is to inherit from DelegatingHandler
, which takes an inner HttpMessageHandler
in its constructor, which it calls in its base SendAsync
implementation.
public class MyHandler1 : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// do something before the inner handler runs (modify the request?)
var response = await base.SendAsync(request, cancellationToken);
// do something after the inner handler runs (modify the repsonse?)
return response;
}
}
Armed with multiple of these, you chain them together in whatever order you want when you construct HttpClient
:
var client = new HttpClient(
new MyHandler1(
new MyHandler2(
new MyHandler3(...))));
Upvotes: 8