How to implement HttpMessageHandler in Web API?

To write a custom message handler, you should derive from System.Net.Http.DelegatingHandler

class CustomMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> 
      SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        IPrincipal principal = new GenericPrincipal(
            new GenericIdentity("myuser"), new string[] { "myrole" });
        Thread.CurrentPrincipal = principal;
        HttpContext.Current.User = principal;

        return base.SendAsync(request, cancellationToken);
    }
}

And call base.SendAsync to send the request to the inner handler.


Here you are creating a HttpMessageHandler which short circuits the request and doesn't let the request pass through the rest of the pipeline. Instead, you should create a DelegatingHandler.

Also there are 2 kinds of message handler pipelines in Web API. One is a regular pipeline in which all requests for all routes pass through and other where one could have message handlers specific to certain routes only.

  1. Try to create a DelegatingHandler and add it to your HttpConfiguration's list of message handlers:

    config.MessageHandlers.Add(new HandlerA())
    
  2. If you want to add a route specific message handler, then you could do the following:

    config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: null,
                handler: 
                       HttpClientFactory.CreatePipeline(
                              new HttpControllerDispatcher(config), 
                              new DelegatingHandler[]{new HandlerA()})
                );
    

This Web Api Poster shows the pipeline flow.