Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API: 'Global' filter not working (ExceptionFilter)

I implemented the exception filter like here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling And registered it globally, like microsoft or stackoverflow-users ( How to add global ASP.Net Web Api Filters? ) explained.

public static void RegisterWebApiFilters(System.Web.Http.Filters.GlobalFilterCollection filters)
{
//other filters
  filters.Add(new MyExceptionFilter());
}

But if I throw an exception, my method is not called. My exception-handling method is called only if I add the attribute [MyExceptionFilter] to the controller-method, but I hoped I can avoid that for all methods by registering the filter globally.

I tried to set a order for the filters, but this had no effect.


Edit: I have noticed, that in the new Wep Api RC the method is called "RegisterGlobalFilters" and this seems to be the MVC filter collection.

If I call

GlobalConfiguration.Configuration.Filters.Add(new MyExceptionFilter());

it works. This is the collection for the Web Api.

Looks like I have to build my own "FilterConfig" class for the web api...

like image 971
user437899 Avatar asked Jun 19 '12 07:06

user437899


1 Answers

Like I mentioned in my question: There are different filter collections. One for MVC and one for the web api.

If you want to add the filter to the web api, add this line of code to the global.asax

GlobalConfiguration.Configuration.Filters.Add(new MyExceptionFilter());
like image 62
user437899 Avatar answered Sep 18 '22 11:09

user437899