Thursday, June 28, 2018

ASP.NET - Sharing state between Action Filters and Controllers

The support for ActionFilters in ASP.NET MVC and Web Api gives you a nice execution pipeline to run code before or after specific stages in the request processing pipeline:

The request is processed through Authorization Filters, Resource Filters, Model Binding, Action Filters, Action Execution and Action Result Conversion, Exception Filters, Result Filters, and Result Execution. On the way out, the request is only processed by Result Filters and Resource Filters before becoming a response sent to the client.

They are a great fit for a lot of use cases, like validation, caching, … and allow you to have an AOP like approach in your controllers. Their are 2 things I find annoying about the usage of ActionFilters:

  1. They introduce an extra layer of abstraction with some hidden magic. It is not always clear what’s going on the request pipeline and what happened in a specific filter.
  2. It is not easy to share state between your action filter and your controller (which can be useful sometimes).

Recently I discovered a great trick that solves the problems above.

Did you know that a controller is also a filter – as it implements both IActionFilter and IAsyncActionFilter interfaces, you can override the related methods and turn your controller into an action filter?

No comments: