Overriding filters in ASP.NET Web API vNext - StrathWeb

Strath

June 16th, 2013

Overriding filters in ASP.NET Web API vNext

One of the more annoying issues in the current version of ASP.NET Web API, is that it’s very difficult to override global/controller scoped filters at action level.

Perhaps you may have logging functionality or authorization filters, that you want to apply globally, and only exclude certain actions from participating in this process.

This problem is remedied in Web API vNext (version 5), and you can try that out with nightly builds.

Getting started

To be able to follow this article, you need to install Web API from the nightly builds feed.

Then you simply install the pre release version:

This should bring in the following packages and versions:

The override functionality was added to Web API (and actually, earlier on to MVC too) on March 15 with this commit.

Overriding filters in ASP.NET Web API

Suppose you have a random filter – it doesn’t really matter what it does – for the demo purposes it will just write to debug output:

In vNext you can apply this filter globally (or at controller level), and then exclude a specific action from having this filter participate in its specific pipeline.

For example, in WebApiConfig.cs we register it globally:

Then, in an individual action, we tell he pipeline to ignore all wider-scoped filters by using the new OverrideActionFiltersAttribute:

Overriding comes in four flavours:

  • – action filter (IActionFilter), through OverrideActionFiltersAttribute
  • – authentication filter (IAuthenticationFilter), through OverrideAuthenticationAttribute
  • – authorization filter (IAuthorizationFilter), through OverrideAuthorizationAttribute
  • – exception filter (IExceptionFilter), through OverrideExceptionAttribute

Each is rather self explanatory, and allows you to break up the pipeline for a specific type of filter. Unfortunately the mechanism is not extensible, and you cannot override a filter by type name (for example you can override all action filters, but if you have multiple action filters, you cannot target a single filter type only).

What happens internally, is that Web API pipeline will select which filters are applicable to your action by comparing the filters scope and check whether any of the filters implements IOverrideFilter interface, and if that’s the case, which of the four mentioned above filter groups it is relevant for. In case there’s a match, the filters with wider scope are being excluded from processing.

Overall this is a very useful functionality. I have been thinking of porting it to existing, stable Web API version (v4 RTM). However, the new update to Web API should come very soon, so it would be a bit of a wasted effort.

Until then you can always grab the functionality from the nightlies and replace your System.Web.Http.

Be Sociable, Share!