I've created a Web Api filter (using System.Web.Http.Filters.ActionFilterAttribute
) but I am unable to get it to work inside of ASP.Net MVC 4. I tried adding it to the RegisterGlobalFilters()
method but that didn't work.
So if one is using Web Api hosted in ASP.Net MVC how does one register filters?
As of MVC 4 RC, the correct class name is HttpFilterCollection:
Instead of using global filters I prefer to do this :
And after that inherit all of api controllers from
CustomizedApiControllerBase
This approach is more expressive in compare with global filters in global.ascx file.The following code, in my Global.asax, works for me:
note that this answer holds true up to MVC 5/Web API 2
Short answer: MVC and Web API filters are not cross compatible, and if you want to register them globally, you must use the appropriate configuration classes for each.
Long answer: ASP.NET MVC and Web API are purposely designed to work in a similar way, but they are in fact different creatures.
Web API lives under the
System.Web.Http
namespace, whereas MVC lives under theSystem.Web.Mvc
namespace. The two will happily live side by side, but one does not contain the other and despite the similarities in the programming model, the underlying implementations are different. Just as MVC controllers and Web API controllers inherit different base controller classes (MVC's is simply namedController
and Web API's is namedApiController
) MVC filters and Web API filters inherit from differentFilterAttribute
classes (both share the same name in this case, but are separate classes which live in their respective namespaces).Web API global filters are registered through the
HttpConfiguration
object available to you in theRegister
method WebApiConfig.cs if you're using a project template with WebActivator:or otherwise in the global.asax.cs:
Mvc global filters are registered by way of a
GlobalFilterCollection
object, which is available to you through theRegisterGlobalFilters
method of FilterConfig.cs for projects that are using WebActivator:or in the global.asax.cs file by way of
GlobalFilters.Filters
collection for those without WebActivator:It's worth noting that in both cases you do not need to inherit from the appropriate
FilterAttribute
type. Web API Filters need only implement the System.Web.Http.IFilter interface, while MVC filter registration checks to ensure that your class inherits one of a handful of filter interfaces defined in theSystem.Web.Mvc
namespace.