In continuation of Part 1 about creating a multitenant application with Entity Framework Code First we are going to see how we can use Interceptors to apply filtering when querying the data in a transparent way for our application. It is highly recommended to read the first part as this post assumes you are already familiar with the problem.
A highly increasing request we have to serve as developers, especially after Software as a Service revolution, is to provide software that is able to handle individual users in one application by separate each user’s data. This feature is called Multitenancy and there are several ways to achieve it. In this series of posts I will try to demonstrate how we can achieve the data isolation by using some advance features of Entity Framework.
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.