Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • ASP.NET MVC - Get Started
  • MVC Architecture
  • MVC Version History
  • Create First MVC App
  • MVC Folder Structure
  • Routing
  • Controller
  • Action method
  • Action Selectors
  • ActionVerbs
  • Model
  • View
  • Integrate Model, View & Controller
  • Model Binding
  • Create Edit View
  • Razor Syntax
  • Html Helpers
  • Exception Handling
  • Validation
  • Layout View
  • Partial View
  • ViewBag
  • ViewData
  • TempData
  • Filters
  • ActionFilters
  • Bundling
  • ScriptBundle
  • StyleBundle
  • Area
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

ASP.NET MVC- Filters

In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides filters for this purpose.

ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes. Filters can be applied to an action method or controller in a declarative or programmatic way. Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface.

MVC provides different types of filters. The following table list filter types, built-in filters, and interface that must be implemented to create custom filters.

Filter TypeDescriptionBuilt-in FilterInterface
Authorization filtersPerforms authentication and authorizes before executing an action method.[Authorize], [RequireHttps]IAuthorizationFilter
Action filtersPerforms some operation before and after an action method executes.

 

IActionFilter
Result filtersPerforms some operation before or after the execution of the view.[OutputCache]IResultFilter
Exception filtersPerforms some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline.[HandleError]IExceptionFilter

To understand the filter in detail, let's take an example of a built-in Exception filter. Exception filter executes when an unhandled exception occurs in your application. The HandleErrorAttribute class is a built-in exception filter class that renders the Error.cshtml by default when an unhandled exception occurs.

Error.cshtml

The following example demonstrates the use of [HandError] attribute on the controller class.

Example: Exception Filter
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        //throw exception for demo
        throw new Exception("This is unhandled exception");
            
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }        
}

Above, the [HandleError] attribute applied to the HomeController. So, an error page Error.cshtml will be displayed if any action method of the HomeController throws an unhandled exception. Please note that unhandled exceptions are exceptions that are not handled by the try-catch blocks.

Filters applied to the controller will automatically be applied to all the action methods of a controller.

Please make sure that the CustomError mode is on in System.web section of web.config.

Example: Set CustomError Mode in web.config
<customErrors mode="On" />

Now, if you run the application, you would get the following error page because we throw an exception in the Index() action method for the demo purpose.

HandleError demo

Register Filters

Filters can be applied at three levels.

Global Level Filters

You can apply filters at a global level in the Application_Start event of the global.asax.cs file by using default FilterConfig.RegisterGlobalFilters() method. The global filters will be applied to all the controller and action methods of an application.

The [HandleError] filter is applied globally in the MVC application by default in every MVC application created using Visual Studio, as shown below.

Example: Register Global Filters
// MvcApplication class contains in Global.asax.cs file 
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
}

// FilterConfig.cs located in App_Start folder 
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

Controller Level Filters

Filters can also be applied to the controller class. Controller level filters are applied to all the action methods. The following filter are applicable to all the action methods of the HomeController, but not on other controllers.

Example: Action Filters on Controller
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

}

Action Method Filters

One or more filters can also applied to an individual action method. The following filter applied only on the Index() action method.

Example: Filters on Action Method
public class HomeController : Controller
{
    [HandleError]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

}

Learn how to create a custom filters.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.