title: MVC 4 Web API register filter
body: <p>I am using MVC 4 Web API to create a service layer for an application.  I am trying to create a global filter that will act on all incoming requests to the API.  Now I understand that this has to be configured differently than standard MVC global action filters.  But I'm having issues getting any of the examples I'm finding online to work.</p>
  
  <p>The problem I am running into is in registering the filter with Web API.</p>
  
  <p>I have my Global.asax set up like this...</p>
  
  <pre><code>public class MvcApplication : System.Web.HttpApplication
  {
      protected void Application_Start()
      {
          AreaRegistration.RegisterAllAreas();
  
          MVCConfig.RegisterRoutes(RouteTable.Routes);
          MVCConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  
          WebApiConfig.RegisterRoutes(GlobalConfiguration.Configuration);
          WebApiConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
      }
  }
  </code></pre>
  
  <p>My standard Mvc routing and filters work correctly.  As does my WebApi routing.  Here is what I have for my webApi filter registration...</p>
  
  <pre><code>public static void RegisterGlobalFilters(System.Web.Http.Filters.HttpFilterCollection filters)
  {
      filters.Add(new PerformanceTestFilter());
  }
  </code></pre>
  
  <p>And here is the PerformanceTestFilter...</p>
  
  <pre><code>public class PerformanceTestFilter : ActionFilterAttribute
  {
      private readonly Stopwatch _stopWatch = new Stopwatch();
  
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
          _stopWatch.Reset();
          _stopWatch.Start();
      }
  
      public override void OnActionExecuted(ActionExecutedContext filterContext)
      {
          _stopWatch.Stop();
          var executionTime = _stopWatch.ElapsedMilliseconds;
          // Do something with the executionTime
      }
  }
  </code></pre>
  
  <p>This filter works fine when it is registered with the standard Mvc GlobalFilterCollection, but when I try to register it with System.Web.Http.Filters.HttpFilterCollection I get an error saying that it is not assignable to parameter type System.Web.Http.Filters.IFilter.</p>
  
  <p>So I'm assuming that my PerformanceTestFilter needs to inherit from something other than ActionFilterAttribute in order to be registered as a webapi filter.  I'm just not sure what that needs to be.</p>
  
  <p>I imagine I will need to create two individual filters to work with mvc and webapi respectively.  If there is a way to create a filter that could be registered to both, that would be great.  But my primary concern is simply to get it working for webapi.</p>
  
  <p>Thanks</p>