Thorsten Westheider
Thorsten Westheider

Reputation: 10932

Can you have more than one HTTP Message Handler for HttpClient?

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 HttpMessageHandlers 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

Answers (1)

Todd Menier
Todd Menier

Reputation: 39309

The easiest way to chain HttpMessageHandlers 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

Related Questions