Loading...

In this post, we will learn about Filter and its type for ASP.Net MVC 4.0 and 5.0.
Filter is used to implement extra logic to perform any task after and before executing the action, exception, authorization etc.

We will see how to work filter and how to create and use it. We can create our own custom filter. This custom filter will implement in action that will authenticate use. If user is authenticated or have access then user can view result of requested action else not.

There are different types of filter that MVC framework supports. 

Types

Used Interface

Description

Authentication Filter

IAuthenticationFilter

Authentication filter is used to authenticate uses. So, authentication filter is used before any other filter or action method. Authentication filter check the user is valid or not.

Authorization Filter

IAuthorizationFilter

Authorization filter is used to check the user have access for a particular action method or not. Its also used before other filters or action method.

Action Filter

IActionFilter

Action filter is used to perform any activity before or after executing the action method.

Result Filter

IResultFilter

Result filter is used before and after action result is executed.

Exception Filter

IExceptionFilter

Exception filter is used when any exception error occurred in our controlleror action method. Exception filter is also used to centralized error handling.



Types of Filter in ASP.Net MVC and Its sequence of Execution

1. Authentication Filter: Authentication filter is used to authenticate the user is valid or not. Or we can say it gives us a confirmation that the user is valid or not. Authentication Filter is used before any other filter or action method. Because, we need to authenticate the use is valid or not. If user is validated true then any other filter or action method will run. To use Authentication Filter we need to implement IAuthenticationFilter interface. 

2. Authorization Filter: Authorization filter is used to authorize the user. Means, Authorization filter is responsible for checking that logged in user have the access of particular page or not (that page user wants to access).
To implement authorization we use Authorize Attribute over our action or controller. To create custom authorization we implement IAuthorization interface.


Reslove ActionFilterAttribute and IAuthenticationFilter form the “using System.Web.MVC.Filters;” namespace.

namespace ActionFiltersinMVC    
{    
    public class AuthAttribute: ActionFilterAttribute, IAuthenticationFilter    
    {        
        public void OnAuthentication(AuthenticationContextfilterContext)    
        {    
            //Logic for authenticating a user    
        }        
        //Runs after the OnAuthentication method    
        public void OnAuthenticationChallenge(AuthenticationChallengeContextfilterContext)    
        {    
            //TODO: Additional tasks on the request    
        }    
    }    
}



3. Action Filter: Action Filter is attribute based filter. We can use action filter to entire controller or a particular action method. Action Filter will execute before and after action start executing or after completed execution.
To implement action filter we need to inherit IActionFilter Interface
IActionFilter Interface have to methods, one is OnActionExecuting and another is OnActionExecuted

OnActionExecuting runs before execution of action and we write a logic here that we wants to perform before executing action. This OnActionExecuting method gives an opportunity to cancel the execution of action. 

OnActionExecuted method runs after execution of action. We can modify the view data that controller action returns. 


Below is the example of custom attribute using action filter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using TeachersTune.Models;
namespace TeachersTune.Attributes
{
    public class SessionTimeOutAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext context = HttpContext.Current;
            if (context.Session != null)
            {
                if (context.Session["UserID"] == null)
                {
                        context.Response.Redirect("Redirect to dashboard page");                 
                 }
                    else
                    {
                        context.Response.Redirect("Redirect to login page");
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
}

4. Result Filter: The OutputCacheAttribute class is an example of Result Filters. These implement the IResultFilter interface which like the IActionFilter has OnResultExecuting and OnResultExecuted. These filters contains logic that is executed before and after a view result is executed. Like if you want to modify a view result right before the view is rendered to the browser.

5. Exception Filter: The HandleErrorAttribute class is an example of ExceptionFilters. These implement the IExceptionFilter interface and they execute if there are any unhandled exceptions thrown during the execution pipeline. These filters can be used as an exception filter to handle errors raised by either your controller actions or controller action results.