Filters In ASP.NET MVC

17:58

Introduction

In this post we will try to explain how we can use custom filters and attributes in an ASP.NET MVC application.

Why We Use Filter In MVC

Sometimes we want to add logic either before or after an action method runs. To support this, ASP.NET MVC provides filters.

Types of Filters in ASP.NET MVC

There are 4 Filters in ASP.NET MVC
i) Authorization filter
ii) Action filter
iii) Result filter
iv) Exception filter

Authorization filter

This filter will be called before action will starts executing. Authorization filter use to authorize a request. We can add the filter object in Global.asax or any other class.
The interface that needs to be implemented for Authorization filter is IAuthorizationFilter. This interface provide us one methods i.e. OnAuthorization.
public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
    void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called";
    }
}

Action filter

This filter will be called before and after the action starts executing and after the action has executed. We can put our custom pre-processing and post-processing logic in this filter.
To implement this filter we need to create a custom filter attribute class and implement the IActionFilter filter interface. This interface provides us two methods OnActionExecuting and OnActionExecuted which will be called before and after the action gets executed respectively.
public class CustomActionAttribute : FilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called";
    }

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

Result filter

This filter will execute before and after the result of the action method has been executed. We can use this filter if we want some modification to be done in the action's result.
To implement the result filters we need to create a custom filter attribute class and implement the IResultFilter interface. This interface provides two methods OnResultExecuting and OnResultExecuted which will be called before and after the action result respectively.
public class CustomResultAttribute : FilterAttribute, IResultFilter
{
    void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called";
    }

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

Exception filter

This filter will be invoked whenever a controller or action of the controller throws an exception. This is particularly useful when we need custom error logging module.
To implement this filter we need to create a custom filter attribute class which implements IExceptionFilter. This interface gives us a methods called OnException which is a perfect place to call the exception logging module and to redirect to some error page.
public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
{
    void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        filterContext.Controller.ViewBag.OnException = "IExceptionFilter.OnException filter called";
    }
}

Execution Order Of Filter

i) IAuthorizationFilter.OnAuthorization
ii) IActionFilter.OnActionExecuting
iii) IActionFilter.OnActionExecuted
iv) IResultFilter.OnResultExecuting
v) IResultFilter.OnResultExecuted
If geting any exception then hit this method
vi) IExceptionFilter.OnException

All Filters In Global.asax

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()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }

    public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called";
        }
    }

    public class CustomActionAttribute : FilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called";
        }

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

    public class CustomResultAttribute : FilterAttribute, IResultFilter
    {
        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called";
        }

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

    public class CustomExceptionAttribute : 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 = "Error",
                ViewData = new ViewDataDictionary(model),
            };
        }
    }
}

Main View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Filter</title>
</head>
<body>
    <div>
        <h1>Execute Filter</h1>
        <ul>
            <li>@ViewBag.OnAuthorization</li>

            <li>@ViewBag.OnActionExecuting</li>
            <li>@ViewBag.OnActionExecuted</li>
            
            <li>@ViewBag.OnResultExecuting</li>
            <li>@ViewBag.OnResultExecuted</li>
        </ul>
    </div>
</body>
</html>

Out Put


Filters
  • IAuthorizationFilter.OnAuthorization filter called
  • IActionFilter.OnActionExecuting filter called
  • IActionFilter.OnActionExecuted filter called
  • IResultFilter.OnResultExecuting filter called

Error View

@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Error";
}

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

Out Put

Controller

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

namespace MVC_Filter.Controllers
{
    public class TestFilterController : Controller
    {
        [CustomAuthorization]
        [CustomAction]
        [CustomResult]
        [CustomException]
        public ActionResult Filter()
        {
            // ------------- For Exception Filter Testing
            //int a = 0;
            //int b = 5;
            //int c = b / a;

            return View();
        }
    }
}

Conclusion

I explain about ASP.NET Filters and its all types hope its helpfull.

You Might Also Like

0 comments