Thorsten Westheider Thorsten Westheider - 9 months ago 95
ASP.NET (C#) Question

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

s very much like outlined in this post, which is for Web API though.

There is a constructor for
taking an
, 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?


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(...))));