Action filters is a very powerful mechanism in an ASP.NET MVC application that gives us the capability of injecting functionality in our application in a centralized and structure way. In this post I am showing how we can create an action filter attribute in order to decorate our controllers to check if the current user has verified his email address after registering in our system through new ASP.NET Identity system. I am going to create two filters as we want to have this functionality in regular MVC controllers and in Web Api controllers as well.
First lets see the code for the regular MVC controllers. What we have to do is just derive from ActionFilterAttribute class that lives in System.Web.Mvc namespace and override the OnActionExecuting method.
The code is very simple as in the case the user has confirmed the email the execution flow continues normally. In the opposite case we are able to redirect the user in a specific action of a controller by replacing the corresponding values.
The code is very similar for Web Api controllers as we can see right below.
Here I choose to implement the async version of OnActionExecuting method. If the user has confirmed the email address then the request is served normally. If the user is not logged in or has not confirmed the email a bad request response is returned containing the additional message.
You can find a complete project containing both of the attributes on Github.