Basics of Filters in MVC

Raj and Mark met again this weekend and continued their discussion of MVC topics from the last topic Basics of Dependency Injection.

Raj: What are filters in MVC? They look like attributes.

Mark: Yes they are the same as C# attributes, applied at the Action and Controller level. These filters are used to inject extra logic into the request processing pipeline, both pre-processing and post-processing logic is injected. They provide simple and the best way to implement the cross-cutting concern.

Raj: What is the cross-cutting concern?

Mark: The functionality that is used all over the application, not only in a single place, filters provide a way to maintain the Separation of Concerns pattern. An example of cross-cutting concerns are logging, authorization and caching.

https://msdn.microsoft.com/en-in/library/ee658105.aspx

Raj: Can you explain more of why we need filters?

Mark: Sometimes you need some action to be performed before or after the action is executed, for example you need to authorize the user before performing an action, you need to log the error after some error happened.

Let us try authorizing.

Let's see with an example. I will create a MVC 4 projectby selecting Basic Templates then adding a HomeController and two action methods (AllUser() and RestrictedUsers()) and add their views as shown in the following screenshot:

Raj, if we run the application, it will run fine as shown below:

Raj : What I can understand from your code is that you have two separate actions with differing types of access, one action for all users and another for privileged users, but you are able to browse both without authorizing.

Mark: okay, to make an action RestrictedUser accessible to an Authorized user, I will just add an attribute to the same action RestrictedUser in the code.

Now I will run the code, let's see:

I am not able to access the RestrictedUser Action. As shown in the screenshot and in the URL, the error screen is for missing the view of the account controller, it comes to this after redirecting from the Unauthorized request.

Raj: you have just added an attribute, then how is it working?

Mark: by default, see the web.config file. It implements Forms Authentication so the Authorize filter validates the request. It is the same as in the following:

Now, I am adding a Login action to the Account Controller (new) to redirect to the login page, not on an error page.

Raj: Its looks good, but what are the benefits of using filters?

Mark: an important reason is to prevent breaking the separation of concerns pattern for cross-cutting concerns. Since the cross-cutting concerns can be applied across the application before/after any action performed or controller, it should be in a single central place. A filter can be applied at an action or controller level that is applied to all the actions of the controller. Also, you can apply multiple filters.

http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx?wa=wsignin1.0

The following example show Multiple Filters, the following will cache the page for 15 seconds.

Similary, HandleError Filter:

On browsing, the preceding action will show the following screen:

Add the following in web.config:

 

  1. <system.web>  
  2.     <customErrors mode="On"></customErrors>  

 

And then HandelError can be applied at the global level always at the Action or Controller Level.

Global Level: in the FilterConfig class as in the following:

And register in Global.aspx.cs as in the following:

The view is already created when creating the Basic MVC Template.

Action or Controller Level

Removed global and applied at an action level as in the following:

Raj: Then, how many types of filters are there?

Mark: There are basically the following four types of filters:

  1. Authorization: Runs first, before any other filter of the action method.
  2. Action: Runs before and after action method.
  3. Result: Runs before and after action result executed.
  4. Exception: Runs only if another filter, the action method, or the action result throw an exception.

In the next meeting/article we will see how to implement these various types of filters and custom filters. This article explained the basics of filters and understood the frequently used action filters, like Authorize, AllowAnonymous, OutputCache and HandleError.