Filtering Requests

The ability to filter requests with attributes has been in ASP.NET since version 1.0, and the ability to add global filters was added in MVC 3. ASP.NET Web API includes both features, although as discussed previously, the filter is global at the configuration level, not at the application level (as there are no such application-wide global features in Web API).

One of the improvements in Web API over MVC is that filters are now part of the asynchronous pipeline, and are by definition always async. If a filter could benefit from being asynchronous — for example, logging exception failures to an asynchronous data source like a database or the file system — then it can do so. However, the Web API team also realized that sometimes being forced to write asynchronous code is unnecessary overhead (especially if you're targeting .NET 4 and don't have access to async and await), so they also created synchronous attribute-based base class implementations of the three filter interfaces. When porting MVC filters, using these base classes is probably the simplest way to get started. If a filter needs to implement more than one stage of the filter pipeline (such as action filtering and exception filtering), there are no helper base classes and the interfaces need to be implemented explicitly.

Developers can apply filters at the action level (for a single action), at the controller level (for all actions in the controller), and at the configuration level (for all actions on ...

Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.