11+ Year IT Industry Experience, Working as Technical Lead with Capgemini | Consultant | Leadership and Corporate Trainer | Motivational and Technical Speaker | Career Coach | Author | MVP | Founder Of RVS Group | Trained more than 4000+ IT professionals | Azure | DevOps | ASP.NET | C# | MVC | WEB API | ANGULAR | TYPESCRIPT | MEAN | SQL | SSRS | WEB SERVICE | WCF... https://bikeshsrivastava.blogspot.in/ http://bikeshsrivastava.com/

What is Filter in MVC ?

Today i am going to explain how to use Filter in MVC application .In this part of blog we will try to describe how we can use custom filters and attributes in an ASP.NET MVC application.

Why we can use Filter in MVC:-
Sometime we need to add logic either before or after an action method runs.To support this type of feature in MVC useing Filter.

Types of Filter in MVC:-

1. Action Filter
2. Authorization Filter
3. Result Filter
4. Exception Filter

1.Authorization Filter:-
This Filter will be execute before action start executing .this  filter is  use to authorize a request for action . We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IAuthorizationFilter
event:- OnAuthorization

Example with code:-

public class AuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
{
    void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.Controller.ViewBag.AuthorizedMessage = "AuthorizationFilter filter is called before action.";
    }
}


2.Action Filter:-
This Filter will be execute before and after action start executing .In this  filter we can use pre-processing and post-processing logic.. We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IActionFilter
event:-  1.OnActionExecuting
               2.OnActionExecuted

Example with code:-

public class ActionFilterAttribute : FilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.ActionMessage1 = "IActionFilter.OnActionExecuted event fire and filter is called";
    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.ActionMessage2 = "IActionFilter.OnActionExecuting event fire and filter called";
    }
}


3.Result Filter:-
This Filter will be execute before and after action start executing .We can use this Filter  in the event that we need some adjustment to be done in the Action outcome.  We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IResultFilter
event:- 1.OnResultExecuted
             2.OnResultExecuting

Example with code:-

public class ResultFilterAttribute : FilterAttribute, IResultFilter
{
    void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.ResultMessage1 = "IResultFilter.OnResultExecuted event fire and filter called";
    }

    void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.ResultMessage2= "IResultFilter.OnResultExecuting event fire and filter called";
    }
}

4.Exception Filter:-
This Filter will be execute whenever any action of the controller throw exception.this  filter is  mainly use to custom error  logging module.We will add the filter object in Global.asax or any other class inside application. These interfaces and event use in this filter.
Interface:- IExceptionFilter
event:-  OnException

Example with code:-

public class ExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        filterContext.Controller.ViewBag.ExceptionMessage = "IExceptionFilter.OnException event fire and filter called";
    }
}

Execution Flow (Order) of Filter:-


IAuthorizationFilter.OnAuthorization
||
IActionFilter.OnActionExecuting
||
IActionFilter.OnActionExecuted
||
IResultFilter.OnResultExecuting IResultFilter.OnResultExecuted
||
//If throwing any exception from action where you are using Exception filter then hit this method
||
IExceptionFilter.OnException



Simple example with MVC application:-

Step 1:-Create Mvc Application and type All filter code inside Global.asax like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MVC_Filter
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {//register all configuration with Filter
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
//Autherization Filter
    public class AuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
    {
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.Controller.ViewBag.AuthorizedMessage = "AuthorizationFilter filter is called before action.";
        }
    }
//Action Filter
    public class ActionFilterAttribute : FilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.ActionMessage1 = "IActionFilter.OnActionExecuted event fire and filter is called";
        }

        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.ActionMessage2= "IActionFilter.OnActionExecuting event fire and filter called";

        }
    }
//Result Filter
    public class CustomResultAttribute : FilterAttribute, IResultFilter
    {
        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.ResultMessage1 = "IResultFilter.OnResultExecuted event fire and filter called";
        }

        void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.ResultMessage2 = "IResultFilter.OnResultExecuting event fire and filter called";
        }
    }
//Execption Filter
    public class ExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        void IExceptionFilter.OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

            var ControllerName = (string)filterContext.RouteData.Values["controller"];
            var ActionName= (string)filterContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(filterContext.Exception, ControllerName , ActionName);
            filterContext.Result = new ViewResult()
            {
                ViewName = "ErrorPage",
                ViewData = new ViewDataDictionary(model),
            };
        }
    }
}

Step 2:-Create a controller and action.

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

namespace Mvc_testFilter.Controllers
{
    public class HomeFilterController : Controller
    {//using Filter as attribute
        [AuthorizationFilter]
        [ActionFilter]
        [ResultFilter]
        [ExceptionFilter]
        public ActionResult Index()
        {
            //  To Exception Filter testing purpose
            //int i = 0;
            //int j = 10;
            //int result = j / i;

            return View();
        }
    }
}
Step 3:-Right Click on =>Index=>AddView=>Create a new view name is"Index".


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Testing page for Filter::</title>
</head>
<body>
    <div>
        <h1>Excuting Filter Attribute</h1>
        <ul>
            <li>@ViewBag.Message</li>
//View bag data is coming from Filter class according error in order(Flow).
            <li>@ViewBag.ActionMessage1</li>
            <li>@ViewBag.ActionMessage2</li>
            
            <li>@ViewBag.ResultMessage1</li>
            <li>@ViewBag.ResultMessage2</li>
        </ul>
    </div>
</body>
</html>

Step 4:-Right Click on =>View Folder=>AddView=>Create a new view name is"ErrorPage".

@model System.Web.Mvc.HandleErrorInfo //use this class on view.

@{
    ViewBag.Title = "ErrorPage";
}

<hgroup class="title">
    <h1 class="error">Error.</h1>
    <h2 class="error">An error occurred while exception throw when processing your request.</h2>
</hgroup>

Step 5:-Check your FilterConfig.cs file inside App_Start folder.

using System.Web;
using System.Web.Mvc;
namespace Tcl_IzoGlass
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

Step 6:-Register FilterConfig class inside Global.asax which is already define above.

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

Step 7:-Set Routing in RouteConfig.cs which is inside App_Start folder like this.

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

namespace Tcl_IzoGlass
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//set routing for filter controller.
                routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "HomeFilter", action = "Index", id = UrlParameter.Optional }
            );          
        }
    }
}

Step 8:-Run application output is:--

Excuting Filter Attributre::

AuthorizationFilter filter is called before action.
IActionFilter.OnActionExecuted event fire and filter is called.
IActionFilter.OnActionExecuting event fire and filter called.
IResultFilter.OnResultExecuted event fire and filter called.
You have just read an article that categorized by title MVC / WEB API by title What is Filter in MVC ?. You can bookmark this page with a URL https://bikeshsrivastava.blogspot.com/2016/07/part-29what-is-filter-in-mvc.html. Thank You!
Author: Bikesh Srivastava - Monday, July 11, 2016

3 comments to "What is Filter in MVC ?"

  1. Thanks for providing this informative information you may also refer.
    http://www.s4techno.com/blog/2016/07/27/introduction-to-sql/

    ReplyDelete
  2. Thanks Bikesh Sir..

    Really #Simple and #Effective approach to help us.Thanks

    ReplyDelete
  3. Given article is very helpful and very usefula and please share articles here hopefully.

    Angular JS Online training
    Angular JS training in hyderabad

    ReplyDelete

Life Is Complicated, But Now programmer Can Keep It Simple.