12

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...

Community
  • 1
  • 1
user437899
  • 8,879
  • 13
  • 51
  • 71

1 Answers1

21

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());
user437899
  • 8,879
  • 13
  • 51
  • 71
  • 1
    Thanks, pointed me in the right direction. A bit daft all these global filter collections... ..and still my exception filter registered for normal controllers doesn't work. Grr. – Luke Puplett Jun 27 '12 at 09:59
  • 1
    yeah I have that line but it's still not firing in some cases.. i can tell it's initialized in the debugger, but it's not triggered on every exception in my web api – Sonic Soul Aug 11 '15 at 20:37