Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add global ASP.Net Web Api Filters?

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?

like image 270
Shane Courtrille Avatar asked Mar 01 '12 17:03

Shane Courtrille


People also ask

How do I register a global filter in Web API?

To apply the filter to all Web API controllers, add it to GlobalConfiguration. Filters. public static class WebApiConfig { public static void Register(HttpConfiguration config) { config. Filters.

How do I add filters to Web API?

Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System. Web. Http.

Where can be apply global filters?

Global Level Filters You can apply filters at a global level in the Application_Start event of the global. asax. cs file by using default FilterConfig. RegisterGlobalFilters() method.


1 Answers

The following code, in my Global.asax, works for me:

public static void RegisterWebApiFilters(System.Web.Http.Filters.HttpFilterCollection filters) {   filters.Add(new MyWebApiFilter()); }  protected void Application_Start() {   RegisterWebApiFilters(GlobalConfiguration.Configuration.Filters); } 
like image 200
Dave Bettin Avatar answered Sep 21 '22 20:09

Dave Bettin