Create User Defined Filters In ASP.NET MVC 5 In Step By Step Process

Introduction

This article explains how to create user defined filters in ASP.NET MVC 5 and how to create log information using filters. Before reading this article, please read the first part of this article at the below link.

Definition

Filters are attributes that can be applied in controller level and action methods level. When we apply it in controller level, it is applicable for all actions within Controllers. Filters are used to add pre or post processing logic to the 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 the things in default filters instead of default filter creating user defined filters. Here, we are creating log information or history details for controllers and action methods using filters. Action filter is a special methodology in MVC  that injects a piece of code or logic. Namespace for filters is “System.Web.Mvc”, and the base class for filters is “FilterAttribute”.

Steps for creating user-defined filter

Step 1

Go to Visual Studio. Open new ASP.NET Web Application, give relevant project name, and click OK. Follow the below screenshot.

new ASP.Net Web Application

Step 2

Select MVC from template type window and click OK. The following screenshot explains how to select template.

MVC

Step 3

Right click on Models folder, select Add, and click Class.... Then, give a useful name to the class to create custom filter.

class

Step 4

After adding the class, add assembly System.Web.Mvc in LogFilter.cs files. LogFilter.cs is class name that is added in Models folder.

code

Step 5

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

code

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 is OOPS concept. The below screenshot explains what the virtual methods inside the ActionFiltersAttribute class are.

code

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 and select Text File. Give it  arelevant name and finally click Add button.

add

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.

code

Step 8

Add the below coding in LogFilter class. This class contains override methods and overrides existing methods of whatever we write in current methods.

Coding

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.IO;  
  7. namespace UserDefinedFilter.Models {  
  8.     public class LogFilter: ActionFilterAttribute, IExceptionFilter {  
  9.         /// <summary>  
  10.         /// This method call before excute Action Method  
  11.         /// </summary>  
  12.         /// <param name="filterContext"></param>  
  13.         public override void OnActionExecuting(ActionExecutingContext filterContext) {  
  14.                 string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "----" + filterContext.ActionDescriptor.ActionName + "--" + "OnActionExecuting";  
  15.                 LogDetails(msg);  
  16.             }  
  17.             /// <summary>  
  18.             /// This method call after excute Action Method  
  19.             /// </summary>  
  20.             /// <param name="filterContext"></param>  
  21.         public override void OnActionExecuted(ActionExecutedContext filterContext) {  
  22.                 string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "----" + filterContext.ActionDescriptor.ActionName + "--" + "OnActionExecuted";  
  23.                 LogDetails(msg);  
  24.             }  
  25.             /// <summary>  
  26.             /// This method call after excute Result   
  27.             /// </summary>  
  28.             /// <param name="filterContext"></param>  
  29.         public override void OnResultExecuted(ResultExecutedContext filterContext) {  
  30.                 string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.RouteData.Values["controller"] + "----" + filterContext.RouteData.Values["action"] + "--" + "OnResultExecuted";  
  31.                 LogDetails(msg);  
  32.             }  
  33.             /// <summary>  
  34.             /// This method call before excute Result   
  35.             /// </summary>  
  36.             /// <param name="filterContext"></param>  
  37.         public override void OnResultExecuting(ResultExecutingContext filterContext) {  
  38.             string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.RouteData.Values["controller"] + "----" + filterContext.RouteData.Values["action"] + "--" + "OnResultExecuting";  
  39.             LogDetails(msg);  
  40.         }  
  41.         void IExceptionFilter.OnException(ExceptionContext filterContext) {  
  42.             string msg = "\n" + DateTime.Now.ToString() + "--" + filterContext.RouteData.Values["controller"] + "----" + filterContext.RouteData.Values["action"] + "--" + "OnException";  
  43.             LogDetails(msg);  
  44.         }  
  45.         private void LogDetails(string logData) {  
  46.             File.AppendAllText(HttpContext.Current.Server.MapPath("~/Log/Log.txt"), logData);  
  47.         }  
  48.     }  
  49. }  
Step 9

We can use user-defined filter in controllers and action methods. Right click on Controllers folder, select Add, and click Controller... Then, give it a name.

controller

Step 10

Add View for corresponding action methods in Demo controller. The below screenshot explains how to add View.

view

Right click on Index action methods, select Add View. The Add View window will open. Then, click Add button.

view

Step 11

We can use our user-defined filter attribute wherever we want. Before using our user-defined filter attribute, we add user defined filter’s namespace in corresponding page and build or compile our solution.

code

Coding
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using UserDefinedFilter.Models;  
  7. namespace UserDefinedFilter.Controllers {  
  8.     public class DemoController: Controller {  
  9.         // GET: Demo  
  10.         [LogFilter]  
  11.         public ActionResult Index() {  
  12.             return View();  
  13.         }  
  14.     }  
  15. }  
Step 12

Finally, compile your solution and run corresponding Controller and Action methods which are added as user-defined attributes.

output
Now, open your Log.txt file. We see our log data. The below screenshot shows log details.

Log.txt file

OnException method will execute when exception occurs in our Controller otherwise it will not execute.

Conclusion

This article explains how to create user-defined filters in a simple way. It is useful to the students and programmers who are newly learning ASP.NET MVC. I hope this article will help many people. 


Similar Articles