Share via


Create User Defined Filters in ASP.NET MVC 5 in Step by Step Process

Introduction

This article explains about how to create user defined filters in ASP.NET MVC 5 in Step by Step way.  This article explains how to create log information using filter. Before reading this article please read first part of this article below link.

ASP.NET MVC 5 Filters Step By Step : Part One

Definition

Filters are attribute that can be applied in controller level and action methods level. When we applied in controller level it is applicable for all actions with in controllers. Filters are used to add pre or post processing logic to action methods.

Background

There are many default filters in ASP.NET MVC. We can create user defined filters based on our requirement except default filters. We cannot do all things in default filters, instead of default filter creating user defines filter.  Here creating log information or history details for controllers and action methods using filters. Action filters is a special methodology in MVC inject peace of code or logic. Namespace for filters is “System.Web.Mvc”. Base class for filters is “FilterAttribute”.

Steps for Creating User Defined Filter

Step 1

Go to Visual Studio, Open new ASP.Net Web Application and give useful project name then click Ok. Follow the bellow screen short.

Step 2

Select MVC From template type window and click ok. Following screen shorts explains how to select template.

Step 3

Right click on model folder select Add and click class then give useful name for class to create custom filter.

Step 4

After adding class adds assembly System.Web.Mvc in LogFilter.cs files. LogFilter.cs is class name which one added class in model folder.

Step 5

>

Now inherit ActionFilterAttribute abstract class and IExceptionFilter interface in LogFilter class.

While creating user defined filters we need to write our concept inside override methods which are in ActionFiltersAttribute class and IExceptionFilter interface because all are virtual methods. Here everything OOPS concept, if know OOPS concept we can learn any things. Below screen shorts explains what the virtual methods inside the ActionFiltersAttribute class are.

Step 6

Now add one folder and add one text file inside the folder. We are going to store the log details inside the text file. Right click on folder, select add and click New Item. Select General, under Visual C# from Add New Item window then select Text File and give useful name. Finally click add button.

 

Step 7

Add LogDetails methods in LogFilter. This method is used to find history of Controller and Action Methods. We need to add System.IO assembly in LogFilter.cs.

Step 8

Add below coding for in LogFilter class. In this class contains override methods and overrides existing methods whatever we write in current methods.

Coding

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.IO;

 

namespace UserDefinedFilter.Models

{

    public class LogFilter : ActionFilterAttribute, IExceptionFilter

    {

       /// <summary>

        /// This method call before excute Action Method

       /// </summary>

       /// <param name="filterContext"></param>

        public override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            string msg = "\n" + DateTime.Now.ToString() +"--"+ filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "----" +

                         filterContext.ActionDescriptor.ActionName + "--" + "OnActionExecuting";

            LogDetails(msg);

        }

 

        /// <summary>

        /// This method call after excute Action Method

        /// </summary>

        /// <param name="filterContext"></param>

        public override void OnActionExecuted(ActionExecutedContext filterContext)

        {

            string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "----" +

                          filterContext.ActionDescriptor.ActionName + "--" + "OnActionExecuted";

            LogDetails(msg);

        }

 

        /// <summary>

        /// This method call after excute Result

        /// </summary>

        /// <param name="filterContext"></param>

        public override void OnResultExecuted(ResultExecutedContext filterContext)

        {

            string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.RouteData.Values["controller"] + "----" +

                          filterContext.RouteData.Values["action"] + "--" + "OnResultExecuted";

            LogDetails(msg);

        }

 

        /// <summary>

        /// This method call before excute Result

        /// </summary>

        /// <param name="filterContext"></param>

        public override void OnResultExecuting(ResultExecutingContext filterContext)

        {

            string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.RouteData.Values["controller"] + "----" +

                           filterContext.RouteData.Values["action"] + "--" + "OnResultExecuting";

            LogDetails(msg);

        }

         void IExceptionFilter.OnException(ExceptionContext filterContext)

        {

            string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.RouteData.Values["controller"] + "----" +

                          filterContext.RouteData.Values["action"] + "--" + "OnException";

            LogDetails(msg);

        }

        private void LogDetails(string logData)

        {

            File.AppendAllText(HttpContext.Current.Server.MapPath("~/Log/Log.txt"),logData);

        }

    }

}

Step 9

We can use in controller and action methods which one we are created user defined filter.  Right click on controller folder select Add and click controller then give controller name.

Step 10

Add view for corresponding action methods in Demo controller. Below screen shorts explains how to add view.

Right click on Index action methods select Add View and Add View window will open then click Add button.

Step 11

We can use our user defined filter attribute, where ever we want. Before using our user defined filter attribute, we add user defined filter’s name space in corresponding page and Build or compile our solution.

Coding

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using UserDefinedFilter.Models;

 

namespace UserDefinedFilter.Controllers

{

    public class DemoController : Controller

    {

        // GET: Demo

        [LogFilter]

        public ActionResult Index()

        {

            return View();

        }

    }

}

Step 12

Finally compile our solution and run corresponding controller and action methods which one added user defined attribute.

Now open our Log.txt file, we see our log data. Below screen shorts shows log details.

OnException method will execute when exception occur in our controller otherwise it will not execute.               

Conclusion

This article explains how to create user defined filters with simple way. It is useful to students and programmer those who are learning newly ASP.NET MVC. I hope this article help to many persons.