title: ASP.NET Web API custom message handler per route and global
body: <p>I have 3 ASP.NET Web API message handlers:</p>
  
  <ul>
  <li>Handler1</li>
  <li>Handler2</li>
  <li>AuthorizeHandler</li>
  </ul>
  
  <p>Handler1 and Handler2 are global (applying to all routes) and one single handler (AuthorizeHandler) applies to one single route.</p>
  
  <p>However I have some issues in implementing this:</p>
  
  <pre><code>  public static void Register(HttpConfiguration config)
      {            
          config.MessageHandlers.Add(new Handler1());  //this will apply to all routes
          config.MessageHandlers.Add(new Handler2());  //this will apply to all routes
  
  
          config.MapHttpAttributeRoutes();
  
  
          config.Routes.MapHttpRoute(
            name: "FreeAPI",
            routeTemplate: "api/free/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
          );
  
  
          config.Routes.MapHttpRoute(
              name: "SecretAPI",
              routeTemplate: "api/{controller}/{action}/{id}",
              defaults: new { id = RouteParameter.Optional },
              constraints: null,
              handler: new AuthorizeHandler()  // this will apply just to this route
                           { 
                              InnerHandler = new HttpControllerDispatcher(config) 
                           }
          );       
  
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
      }
  </code></pre>
  
  <p>Basically what I try to do is create an anonymous route where anybody can call without authentication and one single route that needs authentication in order to access it.</p>
  
  <p>However this implementation I did it doesn't work.</p>
  
  <p>For example I want to have this endpoint: <code>api/free/someanonymouscontroller/someanonymousaction/someanonymousid</code> as anonymous and this endpoint <code>api/somesecurecontroller/somesecureaction/somesecureid</code> as secure that needs authentication.</p>
  
  <p>If I use fiddler to test it, on this endpoint: <code>api/somesecurecontroller/somesecureaction/somesecureid</code> I cannot access it without credentials instead if I use this ednpoint: <code>api/free/somesecurecontroller/somesecureaction/somesecureid</code> (notice the free path) I can access a secure endpoint without the handler to trigger ...</p>