Table of contents
1.
Introduction
2.
Types of filters in MVC
2.1.
Authentication Filter
2.2.
Authorization Filter
2.3.
Result Filter
2.4.
Exception Filter
2.5.
ActionFilter
3.
The Basic ActionFilterAttribute Class
4.
Types of Action Filter
4.1.
Output Cache
4.2.
Handle Error
4.3.
Authorize
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

ASP.NET MVC Action Filter

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The user request is routed to the appropriate action method and controller in ASP.NET MVC. If you wish, you can execute some logic before or after an action method executes in some cases. There are filters for this purpose in ASP.NET MVC.

Different types of filters are available in MVC. Below is the list of all the filters including the built-in filters and interfaces that must be implemented to create custom filters.

Types of filters in MVC

Authentication Filter

The authentication filter is used to confirm the validity of a user for the requested page. Before any other filter is executed, it is the first to be executed. The IAuthenticationFilter interface is implemented by two methods. 

  • OnAuthentication, which will call when user verification is completed. 
  • OnAuthenticationChallenge, which will call after authorization or authentication fail, after an action method is called, and before your view is rendered.
     
public interface IAuthenticationFilter {
    void OnAuthentication(AuthenticationContext filterContext);
    void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}

Authorization Filter

When authorization is needed, this Filter is called. It is called just after the Authentication filter and before the Action filter. This Filter authorizes the user with their role. An authorization filter is implemented by using the "Authorize" attribute. 

IauthorizationFilter implements the IauthorizationFilter interface, which only defines one method, "OnAuthorization," called at authorization time.

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

Result Filter

Like Action Filter, it modifies your view before rendering. It can also perform extra custom logic following rendering. Therefore, it is mainly used for rendering results that you want to display on the view. 

This interface implements IresultFilter, which has two methods, OnResultExecuted and OnResultExecuting, which are called just after your result is created. 

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

Exception Filter

You can use an exception filter, for example, if you need to log exception messages in response to an exception. The "HandleError" attribute provides an inbuilt exception filter. IexceptionFilter implements the IexceptionFilter interface, with only one method defined as OnException, and is called whenever an exception occurs.

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

ActionFilter

Action filters can be applied to either a controller section or the entire controller to modify how an action is executed.

A custom class within ASP.NET MVC allows you to write logic executed before or after an action method runs. Action methods and controllers can be modified using declarative or programmatic filters. They use declarative methods by applying a filter attribute to an action method or controller class and implementing the corresponding interfaces through programming.

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

The Basic ActionFilterAttribute Class

ASP.NET MVC includes a base ActionFilterAttribute class to ease the implementation of custom action filters. Both the IActionFilter and IResultFilter interfaces are implemented in this class, inheriting from Filter.

 An action filter and a result filter are technically the property of a class that inherits from ActionFilterAttribute. Action filter can refer to any filter type in the ASP.NET MVC framework.

You can override the following methods in the base ActionFilterAttribute class:

  • OnActionExecuting – Invoked before a controller action is executed.
  • OnActionExecuted – Invoked after a controller action is executed.
  • OnResultExecuting – Invoked before a controller action result is executed.
  • OnResultExecuted – Invoked after a controller action result is executed.

 

To create a custom filter class, we need to:

Create a new folder in solution, name it "ActionFilter" and add a new class called "CustomActionFilter.cs". To behave this class as an Action filter, we have to inherit the "ActionFilterAttribute" class as the following code shows.

 

ActionFilter\CustomActionFilter.cs

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

namespace ActionFilter {
    public class CustomActionFilter: ActionFilterAttribute {
        public class CustomFilter: ActionFilterAttribute {
            public override void OnActionExecuting(ActionExecutingContext filterContext) {}
            public override void OnActionExecuted(ActionExecutedContext filterContext) {}
            public override void OnResultExecuting(ResultExecutingContext filterContext) {}
            public override void OnResultExecuted(ResultExecutedContext filterContext) {}
        }
    }
}

 

This custom action filter can now be called with our action method in Home Controler. We are just adding the attribute [ActionCustomFilter] to the Index action method of HomeController as follows.

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

Types of Action Filter

Action filter in ASP.NET MVC has:

  • OutputCache 
  • HandleError
  • Authorize

Output Cache

Action filters cache the output of controller actions. Below is an example where the return value is specified to be cached for 10 seconds.

 

ActionFilter/Controller/HomeController.cs

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace ActionFilter {
    public class HomeController: Controller {
        [HttpGet]
        [OutputCache(Duration = 10)]
        public string Index() {
            return DateTime.Now.ToString("T");
        }
    }
}

 

Output:

Handle Error

This action filter handles errors raised by controller actions. Any errors encountered during the execution of the action will lead to creating a view named Error within the Views folder, which will be displayed to the user. 

A controller error will redirect the application to a custom error page in the example below.

 

ActionFilter/Controller/HomeController.cs

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace ActionFilter {
    public class HomeController: Controller {
        [HandleError]
        public ActionResult Index() {
            throw new NullReferenceException();
        }
        public ActionResult About() {
            return View();
        }
    }
}

Authorize

Access to this action filter can be restricted to a specific role or user. This allows only authorized users to log in.

 

ActionFilter/Controller/HomeController.cs

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace ActionFilter {
    public class HomeController: Controller {
        [Authorize]
        public ActionResult Index() {
                ViewBag.Message = "Viewed only to the authourized user";
                return View();
            }
            [Authorize(Roles = "admin")]
        public ActionResult AdminIndex() {
            ViewBag.Message = "Viewed only by users in Admin role";
            return View();
        }
    }
}

Frequently Asked Questions

  1. What is ViewData in MVC?
    String keys are used to store and retrieve ViewData, a dictionary of objects. Controllers and Views exchange data using them. The key-value pairs contained in ViewData must be strings since it is a dictionary. 
    Data can only be transferred from the controller to view, not the other way around.
     
  2. What is ViewBag in MVC?
    In ASP.NET MVC, the ViewBag transfers temporary data from the controller to the view (that is not included in the model). The ControllerBase class, the base class of the Controller class, contains this type of property.
     
  3. Which filters will be executed first and last while using ASP.NET MVC?
    A result filter is executed before and after the result is executed. In addition, when an exception occurs during the processing of a request, the exception filters are executed.
     
  4. Difference between authentication and authorization in MVC?
    To put it simply, authentication is the server's attempt at identifying a user. This typically involves logging in with a username, password, or access token. Servers use authorization to determine whether the claimed user can/cannot perform specific actions.

Key Takeaways

This article introduced the action filters feature of ASP.NET MVC to you. This lesson covered four different filters: authorization filters, action filters, result filters, and exception filters. You have also learned about the base ActionFilterAttribute class.

Apart from this, you can also expand your knowledge by referring to these articles on Features Of ASP Net and ASP Full Form.

You can learn all you need to know about front-end web development by checking out Coding Ninjas Guided Path

Live masterclass