In ASP.NET MVC, controllers define action methods that usually have a one – to – one relationship to possible user interactions, but sometimes you want to logic before an action method is called or after an action method is executed.

ASP.NET MVC provides filters to support this. Filters are custom classes that offer both a declarative and a programmatic way of adding pre-action and post-action behavior to controller action methods.

Action Filters

An action filter is an attribute that can be applied to a controller action or to a whole controller that changes the way the action is carried out . The ASP.NET MVC framework contains multiple action filters.

  • OutputCache ? Caches the output for a specified time of the controller action.

  • HandleError ? handles errors that occur when performing a controller action.

  • Authorize ? Allows you to limit access to a given user or role.

Types of Filters

ASP.NET MVC supports four different filter types-

  • Authorization Filters ? Implements the attribute IAuthorizationFilter.

  • Action Filters ? Implements the attribute IActionFilter.

  • Result Filters ? Implements the attribute IResultFilter.

  • Exception Filters ? Implements the attribute IExceptionFilter.

Filters are executed in the above order. Authorization filters, for example, are always executed before action filters and exception filters are always executed after any other filter type.

Authorization filters are used to implement controller actions authentication and authorization. The Authorize filter, for example, is an example of an Authorization filter. Let’s take a simple example by creating a new MVC project for ASP.Net.

Step 1 ? Open the Visual Studio and click Next menu option File. A new dialog for the project opens.

Step 2 ? Select templates from the left panel, then Visual C# and then Web.

Step 3 ? Select ASP.NET Web Application in the middle panel.

Step 4 ? Enter the MVCFiltersDemo project name in the Name field and click OK to continue and you will see the following dialog to set the initial content for the ASP.NET project.

Step 5 ? To keep things simple, select the empty option and select the checkbox MVC in the section ‘ Add folders and core references’ and click Ok.

A basic MVC project with minimally predefined content will be created.

Step 6 ? To add a controller, right- click the controller folder in the solution browser and choose Add Controller.

The Add Scaffold dialog will be displayed.

Step 7 ? Choose the MVC 5 Controller– Empty option and then click’ Add.’

The Add Controller dialog is shown.

Step 8 ? Set the HomeController name and press the ‘Add’ button..

In the Controllers folder you will see a new C # file ‘HomeController.cs,’ which is also open for editing in Visual Studio.

Apply Action Filter

An action filter can be applied to a single controller or to a whole controller. For example, an OutputCache action filter applies to an action called Index (), which returns the string.

This filter caches the return value of the action for 15 seconds. To make this a working example, let’s change the control class by using the following code to change the action method called Index.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        [OutputCache(Duration = 15)]

        public string Index()
        {
            return "This is ASP.Net MVC Filters Tutorial";
        }
    }
}

You will see that the browser displays the result of the Index action method when you run this application.

Let’s add another mode of action that shows the current time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        [OutputCache(Duration = 15)]

        public string Index()
        {
            return "This is ASP.Net MVC Filters Tutorial";
        }

        [OutputCache(Duration = 20)]
        public string GetCurrentTime()
        {
            return DateTime.Now.ToString("T");
        }
    }
}

Request the following URL, http:/localhost:4626/Home/GetCurrentTime, and the following output is provided to you.

You will see the same time when you refresh the browser because the action is cached for 20 seconds. It will be updated after 20 seconds when you refresh it.

Custom Filters

ASP.NET MVC framework provides a basic class called the ActionFilterAttribute to create your own custom filter. This class implements the interfaces IActionFilter and IResultFilter and both are derived from the filter class.

Let’s look at a simple example of a custom filter by creating a new folder with ActionFilters in your project. Add one class to the ActionFilters folder by right clicking and select Add Class.

Enter ‘MyLogActionFilter’ in the field name and press the button ‘Add’.

This class is derived from the base class ActionFilterAttribute and overrides the following method. The complete implementation of the MyLogActionFilter is as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Diagnostics; namespace MVCFiltersDemo.ActionFilters { public class MyLogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { Log("OnActionExecuting", filterContext.RouteData); } public override void OnActionExecuted(ActionExecutedContext filterContext) { Log("OnActionExecuted", filterContext.RouteData); } public override void OnResultExecuting(ResultExecutingContext filterContext) { Log("OnResultExecuting", filterContext.RouteData); } public override void OnResultExecuted(ResultExecutedContext filterContext) { Log("OnResultExecuted", filterContext.RouteData); } private void Log(string methodName, RouteData routeData) { var controllerName = routeData.Values["controller"]; var actionName = routeData.Values["action"]; var message = String.Format( "{0} controller:{1} action:{2}", methodName, controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); } } }

Now, use the following code to apply the log filter to the HomeController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        [OutputCache(Duration = 15)]

        public string Index()
        {
            return "This is ASP.Net MVC Filters Tutorial";
        }

        [OutputCache(Duration = 20)]
        public string GetCurrentTime()
        {
            return DateTime.Now.ToString("T");
        }
    }
}

Run the application and watch the output window.

As shown in the screenshot above, the steps of the action processing are logged into the Visual Studio output window.