There are different types of filters available in MVC.

What are filters in MVC?

Filters are used to execute custom logic before or after executing the action method. ASP.NET MVC provides filters for this purpose. ASP.NET MVC Filter is a custom class where we can write custom logic to execute that before or after an action method is executed.

Types of filters in MVC

Action Filters

If we have multiple filters, this is the sequence for execution.

"Filter Overrides" in MVC

ASP.NET MVC 5 has a new feature called "Filter Overrides" which allows you to clear or replace certain filter types created in higher scopes.

What are the "filter overrides" attributes in ASP.NET MVC 5?

These all implement IOverrideFilter, which is an interface you can implement on your own classes to create custom FilterAttributes.

How to create Custom Filters in MVC?

We can create our own custom filters or attributes either by implementing the ASP.NET MVC filter interface or by inheriting and overriding methods of ASP.NET MVC filter attribute class if available.

When to use Filters in MVC?

Filters in MVC are used to perform the following common functionalities in an 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

How to configure filters in ASP.NET MVC?

We can configure our custom filter in an application at three levels.

Global level

Do this 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);
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Controller level

Do this by putting your filter on the top of the controller name.

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    public ActionResult Login()
    {
        return View();
    }
}

Action Level

Do this by putting your filter on the top of the action name as shown below.

[Authorize(Users = "Students,Parents,Teachers")]
public ActionResult Login()
{
    return View();
}