Filters in MVC

Filters in MVC

In this article, I am going to give you an overview of Filters in MVC application. As part of this article, we are going to discuss the following pointers.

  1. What are the Filters in ASP.NET MVC?
  2. Why we need Filters?
  3. What are the different Types of Filters?
  4. Different ways to use Filters
  5. What is the need for Custom Filters in MVC application?
What are Filters in ASP.NET MVC Application?

As of now, we discussed when a client makes a request, then that request comes to Routing Engine and then the Routing Engine navigates that Request to the Controller. The controller then selects the appropriate action method to execute. So, it is the Controller action method which is going to handle the incoming request and send the response back to the client who initially made the request as shown in the below image,

Filters in ASP.NET MVC Application

But what will you do, if you want to execute some code or logic either before or after the action method executed as shown in the below image?

Executing Logic Before or After Action Method is Executed

If that is what you want to achieve then you need to use Filters in ASP.NET MVC application. The Filters in ASP.NET MVC are the attribute which allows us to inject some logic or code which is going to be executed either before or after an action method is invoked.

Why do we need to use Filters in MVC?

Basically, ASP.NET MVC Filters are used to perform the following common functionalities in your application.

  1. Caching
  2. Logging
  3. Error Handling
  4. Authentication and Authorization, etc.
What are the Different Types of Filters in MVC?

The ASP.NET MVC5 framework provides five different types of Filters. They are as follows

  1. Authentication Filter (Introduced in MVC 5)
  2. Authorization Filter
  3. Action Filter
  4. Result Filter
  5. Exception Filter

Note: This is also the order of the execution of Filters if more than one filter is applied. But the point that you need to remember is the Exception Filter can be executed at any point of time when there is an unhandled exception occurred in your application.

What are the Predefined Filters?

Some of the filters are already built by ASP.NET MVC framework and they are ready to be used. For example

  1. Authorize
  2. ValidateInput
  3. HandleError
  4. RequireHttps
  5. OutputCache, etc
Can we Create Custom Filters in MVC?

Yes, You can create custom filters in MVC. If the built-in filters do not serve your purpose then you can create your own custom filter as per your business requirements. You can create the Custom Filter for all the above five different categories of Filters.

Where we can configure the filters in ASP.NET MVC?

You can configure the filters at three different levels of our application. They are as follows

  1. Global Level
  2. Controller Level
  3. Action Level
Global Level:

Here you need to register the Filter within the Application_Start() method of Global.asax.cs file as shown below. As we know this is the first method of our application which is going to be executed when the application starts.  

protected void Application_Start()
{
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}

Note: When you register a filter at Global level, then it is applicable to all the Action Methods of all the Controllers of your MVC application.

Controller Level:

Here you need to apply the Filter at the top of the controller name as shown below.

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    //Code
}

Note: When you apply the filter at the Controller level, then it is applicable to all the action methods of that controller only.

Action Level:

Here you need to apply the filter on the top of the action method name as shown below.

public class UserController : Controller
{
    [Authorize(Users = "User1,User2")]
    public ActionResult LinkToLogin(string provider)
    {
        // Code
        return View();
    }
}

Note: When you apply the filter to a particular action method, then it is only applicable to that particular action method.

As we already discussed we have five types of Filters in ASP.NET MVC application. Let us discuss the overview of each filter. Here we only discuss the purpose and when that filter is going to be executed and from our next article onwards we will discuss each filter in details.

Filters Types in ASP.NET MVC

Authentication Filters

The Authentication filter is the first filter that is going to be executed before executing any other filter or action method. This filter checks that the user from where the request is coming is a valid user or not. The Authentication filters in MVC implements the IAuthenticationFilter interface. 

Note: This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create a Custom Authentication filter.

The definition of this interface is given below-

Authentication Filters in MVC

As of now, there is no in-built Authentication Filter provided MVC Framework. If you want to create Custom Authentication Filter then you need to implement the IAuthenticationFilter interface. In a later article, we will discuss how to Create Custom Authentication Filters in details with real-time examples.

Authorization Filters

The Authorization Filters executed after the Authentication Filter. This filter is used to check whether the user has the rights to access the particular resource or page. The built-in AuthorizeAttribute and RequireHttpsAttribute are examples of Authorization Filters.

The Authorization Filters in MVC implements the IAuthorizationFilter interface. The definition of IAuthorizationFilter interface is given below.

Authorization Filters in MVC

If you want to create a Custom Authorization Filter then you need to implement the IAuthorizationFilter interface. We will discuss Authorization Filters in details with real time example in our upcoming articles.

Action Filters

The Action Filter will be executed before the action method starts executing or after the action has executed. So, if you want to execute some custom logic which should be get executed before and after an action method executes, then you need to use the Action Filters in MVC applications.

The Action filters implement the IActionFilter interface that has two methods OnActionExecuting and OnActionExecuted. The definition of IActionFilter interface is given below.

Action Filters in MVC

We will discuss Action Filters in MVC with real time example in our upcoming articles.

Result Filters

The Result filters in MVC application are executed before or after generating the result for an action. Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult abstract class. Result filters are called after the Action filters. The in-built OutputCacheAttribute is an example of Result Filters.

The Result Filters in MVC implements the IResultFilter interface. The definition of the IResultFilter interface is given below.

Result Filters in ASP.NET MVC

The IResultFilter interface provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively. If you want to create a Custom Result Filter then you need to implement the IResultFilter interface.

We will discuss Result Filters in details with real time example in our upcoming articles.

Exception Filters:

The Exception filters are executed when there is an unhandled exception occurs during either the execution of actions or filters. The in-built HandleErrorAttribute class is an example of Exception Filters.

The IExceptionFilter interface is used to create Custom Exception Filter which provides the OnException method which will be executed when there is an unhandled exception occurs during the actions or filters execution. The definition of IExceptionFilter is given below.

Exception Filters in ASP.NET MVC

In the next article, I am going to discuss Exception Filters in MVC application with one real-time example. I hope this article gives you a very good understanding of the Filters Overview in ASP.NEt MVC Application.

Leave a Reply

Your email address will not be published. Required fields are marked *