This article will help you to understand the what is filters in Asp.Net MVC and why we should use it. Before moving to the actual definition of filters, don’t confuse with its name, it is not going to filter your data from some list of data.

Basically Filters in Asp.Net MVC is pre-processing and post-processing custom business logic which helps us to add or manipulate our data just before an action is being executed and just after an action has executed. Pre-Processing and Post-Processing logic is not written in any action, we just write it inside the filters. Say for example where we can use filters like logging visitor details who is accessing our website or some logging information after action executed or authentication/authorization logic for the user which is not basically part of our action method.

This article will demonstrate about what filters are, why we use it and how to create custom filters in Asp.Net MVC. Filters can be defined as a controller level, action level or global level. To define it controller or action level, we have to use it as an attribute as follows.

To define, your filters as a controller level, just decorate filter as an attribute with a controller.

[CustomFilter]
public class HomeController : Controller

 

To define, your filters as an action level, just decorate filter as an attribute with action method.

[CustomFilter]
public ActionResult Index()

To define, your filters as a global level, just add the filter in a GlobalFilterCollection object in FilterConfig.cs file which located in the App_Start folder of Asp.Net MVC application.

namespace FilterExample
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new CustomFilter());
        }
    }
}

And this is already registered on Application_Start method inside Global.asax.cs file as follows.

namespace FilterExample
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

 

There are different types of filters available in Asp.Net MVC based upon their uses in Asp.Net MVC page life cycle and these are as following.

Authentication Filter: As the name says that it is an authentication filter used for Authentication the valid user while processing the requested page. It is the first filter which executes before any other filter is being executed.  It implements IAuthenticationFilter interface which has defined two methods as follows. One is OnAuthentication, which will call at the time user verification and another one is OnAuthenticationChallenge, which will call after Authentication or Authorization is failed and an action method gets called and before your view is being rendered.

public interface IAuthenticationFilter
{
    void OnAuthentication(AuthenticationContext filterContext);
    void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}

 

Authorization Filter:  This filter is being called when authorization is required. Basically, the sequence of calling this filter is just after the Authentication filter and just before an action filter gets called. It uses to Authorize the user with his/her role. For example “Authorize” attribute is used to implement Authorization filter. Authorization filter implements IauthorizationFilter interface which has only one method defined “OnAuthorization” which will call at the time of authorization.

public interface IAuthorizationFilter
{
    void OnAuthorization(AuthorizationContext filterContext);
}

 

Action Filter: This filter is really helpful when we have to perform some pre or post-processing logic with action method executed. Yes, action filter gets called before an action method gets executes and after an action method get executes. Action filter implements IactionFilter interface which has two methods defined as OnActionExecuted and OnActionExecuting. OnActionExecuting method calls just before an action method getting called and OnActionExecuted method calls just after an action method getting called.

public interface IActionFilter
{
     void OnActionExecuted(ActionExecutedContext filterContext);        
     void OnActionExecuting(ActionExecutingContext filterContext);
}

 

Result Filter: It is much similar to Action Filter and uses to modify your view before rendering or perform some extra custom logic just after to render the view. So, it means, it mainly uses for your result which you want to render on the view.  It implements IresultFilter interface which has two methods similar to ActionFilter as OnResultExecuted which is called just after your result created and OnResultExecuting which is called just before your result creating. For example, there is inbuild Result filter and gets used using “OutputCache” attribute that is used to cache your page response.

public interface IResultFilter
{
   void OnResultExecuted(ResultExecutedContext filterContext);
   void OnResultExecuting(ResultExecutingContext filterContext);
}

 

Exception Filter: This filter calls when some exception occurred. For example, if we would like to log exception messages when an exception occurred then we can use exception filter. There is inbuilt exception filter is available and that is “HandleError” attribute. This implements IexceptionFilter interface which has only one method defined as OnException and it gets called when any exception generated.

public interface IExceptionFilter
{        
   void OnException(ExceptionContext filterContext);
}

 

Custom Action Filters

There are several inbuilt filters available with their uses. But if we want to add some custom logic as per our requirement then we can create custom action filter as per our requirements. In this demonstration, we will see, how to create custom action filter to track our visitor data and update page view once page got a view.

Before moving to Visual Studio to create an application. Just create one database and few tables that will use further in this demonstration. Following scripts, we can use for creating database and tables.

CREATE DATABASE Demo
GO

USE Demo

CREATE TABLE Visitors (Id INT PRIMARY KEY IDENTITY(1,1), IP_Address VARCHAR(50), Location VARCHAR(255), Created_date DATETIME)

CREATE TABLE PageDetails(Id INT PRIMARY KEY IDENTITY(1,1), PageName VARCHAR(50), Views INT)

Visitors table will contain information about real-time visitors who visit our sites and the PageDetails table will show page view of the particular page.

So we have database and tables ready for demonstration. Now just create an Asp.Net MVC application as we create usually in Visual Studio.To create a new project just follows the following instructions.

  1. Open Visual Studio 2013/2015/2017
  2. Go to File >> New >> Project.
  3. From the "New Project" window, select “ASP.NET Web Application”.
  4. Browse the location to save the project and provide a suitable name and click "OK".
  5. From the next window, select MVC as a template and click "OK".

Create a new folder in solution, name it “filters” and add new class name it “CustomFilter.cs”. To behave this class as an Action filter, we have to inherit “ActionFilterAttribute” class as following code shows.

using System;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace FilterExample.filters
{
    public class CustomFilter : ActionFilterAttribute
    {
        //     Called by the ASP.NET MVC framework before the action method executes.      
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        { 
        }      

        //     Called by the ASP.NET MVC framework after the action method executes.     
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        { 
        }  

        //     Called by the ASP.NET MVC framework before the action result executes.      
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
        }

        //     Called by the ASP.NET MVC framework after the action result executes.        
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
        }
    }
}

As we will perform some database operation here to add data into the database. So, right click to solution add a new item as “Ado.Net Entity Data Model” and through wizard just make a connection with defined tables as above.  In this example, we have created “DemoEntities” to access database tables.

Just update, following line of codes inside the OnActionExecuting method. Basically here we are getting visitor details like their IP address and Location based on some parameters and once these data are available, we add it to Visitors tables. This logic will perform before any action method is being executed.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
 string varVisitorCountry = string.Empty;
 string varIpAddress = string.Empty;

 varIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 if (string.IsNullOrEmpty(varIpAddress))
 {
  if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  {
   varIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  }
 }

 if (varIpAddress == "" || varIpAddress == null)
 {
  if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
  {
   varIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  }
 }

 WebRequest varWebRequest = WebRequest.Create("http://freegeoip.net/xml/" + varIpAddress);
 WebProxy px = new WebProxy("http://freegeoip.net/xml/" + varIpAddress, true);
 varWebRequest.Proxy = px;
 varWebRequest.Timeout = 2000;

 try 
 {
  WebResponse rep = varWebRequest.GetResponse();
  XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
  DataSet ds = new DataSet();
  ds.ReadXml(xtr);
  varVisitorCountry = Convert.ToString(ds.Tables[0]);
 }
 catch {}

 using(var db = new DemoEntities()) 
 {

  db.Visitors.Add(new Visitor() 
  {
   IP_Address = varIpAddress,
    Location = varVisitorCountry,
    Created_date = DateTime.Now
  });

  db.SaveChanges();
 }
}

 

Now move to the OnActionExecuted method and update the code with following code. This code will be executed after the action method is being executed. Here we have written logic to update the number of page view inside the database table”Pagedetails”. 

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
  using(var db = new DemoEntities()) 
  {
   var pageDetail = db.PageDetails.Where(x => x.PageName == "Home").FirstOrDefault();
   if (pageDetail != null)
   {
    if (pageDetail.Views != null) 
    {
     db.PageDetails.FirstOrDefault().Views += 1;
    }
    else
    {
     db.PageDetails.Add(new PageDetail()
     {
      PageName = "Home",
       Views = 1
     });
    }
   }

   db.SaveChanges();
}

 

Now its time to call this custom action filter with our action method in Home Controler. So, we are just decorating our Index action method of HomeController with [CustomFilter] attribute as follows.

public class HomeController : Controller
{
    [CustomFilter]
    public ActionResult Index()
    {
        return View();
    }
}

Now run the application and check the database, after running the application, we have refreshed the page once more. So, our page has reloaded. When we move to the database and select both tables to see the data, we will find following output.

Asp.net mvc filters

 

Here we can see that "Visitors" table is containing the records for each visitors and "PageDetails" table is containing the page view based on the page name and these information has added by the custom filter.as we have created above. Visitors information is adding in the database as pre-processing logic and page view information is adding as post-processing logic.

Conclusion

So, today, we learned what are filters in Asp.Net MVC and why should we use it. We have also seen how to create a custom filter and use it.

I hope, this post will help you. Please put your feedback in the comments section which will help me to improve myself for the next post. If you have any doubts, please ask; and if you like this post, please share it with your friends.