Secure your ASP.NET Web API with message handlers.

Message Handlers, commonly known as DelegatingChannels in WCF or DelegatingHandlers in ASP.NET Web API, provide an essential tool for developers to access and manipulate an incoming message prior to that message reaching the HttpControllerDispatcher.

Why would this be useful? Well, you could use a custom message handler for authentication, usage metrics, request logging, the list goes on. I’ll show you an example on basic authentication via simple key validation, but it could be easily extended for OAuth, or some other form of authentication.

Here is a graphic to better illustrate exactly how the message handlers play into the overall process flow of the incoming HTTP request.

ASP.NET Web API Request Pipeline

Now for some code. The first thing we need to do is create a derived class from System.Net.Http.DelegatingHandler, I shall call it ApiKeyHandler. We will then need to do the following.

  • override the Task SendAsync method from the parent class.
  • retrieve the API key from the query string.
  • validate the key against a data store (in this case I’ll be using a simple database repository class)
  • if the key is not valid, throw a 403 Forbidden response.
  • call the base implementation of SendAsync to continue the request down the pipeline.

This may sound like a lot, in reality it’s quite the simple method.

   public class ApiKeyHandler : DelegatingHandler
            private static readonly IApiKeyRepository _repository = new IApiKeyRepository();

            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

                //get query string from url QS
                string apikey = request.RequestUri.ParseQueryString().Get("apikey");

                //check for valid key
                if (!_repository.ValidateKey(apiKey))
                    //return 403 forbidden.
                    HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid API Key.");
                    throw new HttpResponseException(response);

                //continue request as normal
                return base.SendAsync(request, cancellationToken);



That’s all there is to it. Now obviously this is just an example and shouldn’t be copy & pasted into your code base without proper testing, but it should provide you with the base you need to implement whatever logic you need for processing (and in the case authenticating) requests accordingly before they get to your controller.

One thought on “Secure your ASP.NET Web API with message handlers.

  1. Edmund

    I really was initially researching for suggestions for my personal blog and encountered
    ur blog, “Secure your ASP.NET Web API with message handlers.
    | Twisted Bits”, do you really mind if perhaps I work with a number
    of of your own concepts? With thanks ,Willa

Comments are closed.