Understanding ASP.NET MVC Filters and Attributes

Understanding ASP.NET MVC Filters and Attributes

21 Jun 2024
Intermediate
342K Views
13 min read

MVC Filters and Attributes: An Overview

ASP.NET MVC provides a simple way to inject your piece of code or logic either before or after an action is executed. This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters(filter interface) and can contain your piece of code or logic. 

You can make your custom filters or attributes either by implementing the ASP.NET MVC filter interface or by inheriting and overriding methods of the ASP.NET MVC filter attribute class if available. In this MVC Tutorial, we will explore more about Filters and Attributes which will include types of filters in asp.net mvc, asp.net mvc5 filters, and making custom filters in mvc5. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.

What are filters in MVC?

  • These are used to execute custom logic before or after executing the action method.
  • ASP.NET MVC Filter is a custom class where you can write custom logic to execute that before or after an action method is executed.

When to use Filters?

Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.

  1. Custom Authentication

  2. Custom Authorization(User-based or Role based)

  3. Error handling or logging

  4. User Activity Logging

  5. Data Caching

  6. Data Compression

Types of Filters

The ASP.NET MVC framework provides five types of filters.

  1. Authentication filters (New in ASP.NET MVC5)

  2. Authorization filters

  3. Action filters

  4. Result filters

  5. Exception filters

Types of Filters

Read More: MVC Interview Questions and Answers

Authentication Filters

  • This filter is introduced with ASP.NET MVC5.
  • The IAuthenticationFilter interface is used to create a CustomAuthentication filter. T
  • The definition of this interface is given below-
public interface IAuthenticationFilter
{
 void OnAuthentication(AuthenticationContext filterContext);

 void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}

You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
 public void OnAuthentication(AuthenticationContext filterContext)
 { 
 //Logic for authenticating a user
 }
 //Runs after the OnAuthentication method
 public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
 { 
 //TODO: Additional tasks on the request
 }
}

Authorization Filters

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-

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

The AuthorizeAttribute class provides the following methods to override the CustomAuthorize attribute class.

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
 protected virtual bool AuthorizeCore(HttpContextBase httpContext);
 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
 public virtual void OnAuthorization(AuthorizationContext filterContext);
 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}

In this way, you can make your CustomAuthorize filter attribute either by implementing the IAuthorizationFilter interface or by inheriting and overriding the above methods of the AuthorizeAttribute class.

Action Filters

Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.


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

Result Filters

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create a Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.

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

Exception Filters

Exception filters are executed when an exception occurs during the actions or filter execution. The IExceptionFilter interface is used to create an Exception Filter, which provides an OnException method that will be executed when an exception occurs during the actions or filter execution.

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

ASP.NET MVC HandleErrorAttribute filter is an Exception filter that implements IExceptionFilter. When the HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.

Order of Filter Execution

All ASP.NET MVC filters are executed in an order. The correct order of execution is given below:

  1. Authentication filters

  2. Authorization filters

  3. Action filters

  4. Result filters

Configuring Filters

You can configure your own custom filter into your application at the following three levels:

  1. Global level

    By registering your filter into the Application_Start event of Global.asax.cs file with the help of the FilterConfig class.

    protected void Application_Start()
    {
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
    
  2. Controller level

    By putting your filter on the top of the controller name as shown below-

    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
     //
    }  
  3. Action Level

    By putting your filter on the top of the action name as shown below-

    public class UserController : Controller
    {
     [Authorize(Users="User1,User2")]
     public ActionResult LinkLogin(string provider)
     {
     // TODO:
     return View();
     }
    } 

How to make custom filters in mvc5?

Now, We will learn how to create custom filters in MVC 5 Now, Let's create a Custom Action Filter that implements the pre-processing and post-processing logic. It will inherit from the ActionFilterAttribute class and also implement the IActionFilter interface.

ActionFilterAttribute :

it has four methods these are as follows
ActionFilterAttribute :
1.OnActionExecuting:
This method is called just before the action method is going to be called.
2.OnActionExecuted:
This method is just after the action method is called.
3.OnResultExecuting:
This method is called just before the result is executed; it means before rendering the view.
4.OnResultExecuted:
This method is called just after the result is executed, which means after rendering the view.

Example:

Let's elaborate on this in C# Compiler
using System.Web;  
using System.Web.Mvc;  
using Microsoft.AspNet.Identity;  
using System.Web.Routing;  
  
namespace FilterExample  
{  
    public class AuthorizationPrivilegeFilter : ActionFilterAttribute  
    {  
  
        public override void OnActionExecuting(ActionExecutingContext filterContext)  
        {  
  
            AuthorizationService _authorizeService = new AuthorizationService();  
            string userId = HttpContext.Current.User.Identity.GetUserId();  
            if (userId != null)  
            {  
                var result = _authorizeService.CanManageUser(userId);  
                if (!result)  
                {  
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{{ "controller", "Account" },  
                                          { "action", "Login" }  
  
                                         });  
                }  
            }  
            else  
            {  
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{{ "controller", "Account" },  
                                          { "action", "Login" }  
  
                                         });  
  
            }  
            base.OnActionExecuting(filterContext);  
        }  
  
    }  
}    
Conclusion:
So in this article, we have learned the ASP.NET MVC filter while extending the ASP.NET MVC framework. I hope you enjoyed learning these concepts while programming with Asp.Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Level up your career in MVC with our ASP.Net Core Certification.

FAQs

The Attribute filter allows you to limit the issues in a structure based on the values in a specific attribute. To apply an Attribute filter to a structure, open the Automation menu, select a filter, and choose the Attribute filter

  • Authorization filters – Implements the IAuthorizationFilter attribute.
  • Action filters – Implements the IActionFilter attribute.
  • Result filters – Implements the IResultFilter attribute.
  • Exception filters – Implements the IExceptionFilter attribute.

MVC's exception filters make it possible to handle all controller method exceptions in one place. 
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this