Filters in Asp.Net MVC

by Sachin Singh


Posted on Sunday, 05 April 2020

Tags: Filters and their types in mvc Filters in MVC filter filters filters in mvc filters in asp.net mvc filters in C# mvc what is filters in mvc

In Asp.Net MVC filters are used to inject some pre-processing or post-processing logic in the Asp.Net MVC pipeline. For example, if we want to authenticate a request before executing an action method, it means we want to inject a pre-processing logic in the Asp.Net MVC life cycle. Similarly, if we want to alter the HTML (view result) before rendering it to the screen, it means we want to inject some post-processing logic in the Asp.Net MVC pipeline.

In Asp.Net WebForm we were frequently using HttpHandlers and HttpModule for injecting pre-processing or post-processing logic, we can still implement HttpHandlers or HttpModules in Asp.Net MVC but in most cases, the filters provided by MVC can do the job, we even can extend the built-in Filters or can create or own custom filters as per the requirement. In short when the easier thing is available then why go for the complex.

Each filter is an attribute that can be applied over any particular action or to the controller, if it is applied over a controller it means it will work for every Action within that controller. The filters can even be registered at the application level (global level) which will work for every Action within any controller.

Types of Filters

Asp.Net MVC provides following Filters.

Authorization Filter:- Authorization filters are used to authenticate or authorize a user. This filter implement the IAuthorizationFilter interface.

Action Filter:- ActionFilter implements IActionFilter interface ,and are used to change the flow of execution of an Action method. Following Action methods are provided by MVC.

• Output Cache:- This filter cashes the output of an action method for certain duration.

         [OutputCache(Duration=30)]
        public ActionResult Index()
        {
            EmployeeVM evm = new EmployeeVM();
            evm.employees = new List<employee>(){
                new Employee(){Id=1,Name="emp1"},
                new Employee(){Id=2,Name="emp2"},
                new Employee(){Id=3,Name="emp3"},
            };
           
            return View(evm);
        }

In the above code the output of Index Action will be cashed for 30 seconds.

• HandleError:- This filter is used to show specific error page if any exception occurs during the execution of Action Method.

        [HandleError(View="error.cshtml")]
        public ActionResult Index()
        {
            EmployeeVM evm = new EmployeeVM();
            evm.employees = new List<employee>(){
                new Employee(){Id=1,Name="emp1"},
                new Employee(){Id=2,Name="emp2"},
                new Employee(){Id=3,Name="emp3"},
            };
           
            return View(evm);
        }

In the above example if any exception is thrown (exception means error which is not handled by try catch block) then specified view will be displayed.If we do not specify view name then view resides under Shared folder with Error.cshtml will be displayed.

HandleError can also be registered globally in FilterConfig.cs.To make HandleError work below settings is also necessary in webconfig.


  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
         
        }


        <system.webserver>
        <httperrors errormode="Custom">
        <remove statuscode="404" />
        <error statuscode="404" path="/error/Error404" responsemode="Redirect" />
      </httperrors>
      <modules>
        <remove name="FormsAuthenticationModule" />
     </modules>
   </system.webserver>

Here Error404 is view name ,which is displayed when a resource is not found.

• Authorize:- This filter is used to authenticate and authorize a user, if a user is authenticated and have the permission then only he can access the page.

            [Authorize]
        public ActionResult GetCustomer()
        {
            CustomerVM cvm = new CustomerVM();
            cvm.customers = new List<customer>(){
                new Customer(){Id=1,Name="customer1"},
                new Customer(){Id=2,Name="customer2"},
                new Customer(){Id=3,Name="customer3"},
            };
            return View(cvm);
        }

If the user is not logged in and try to access the above method then he will be redirected to login page provided Forms Authentication is enabled otherwise it will throw 401 error stating unothorized access.

Result Filters:- Result filters implement IResultFilter and are used to inject logic before or after the execution of viewresult .

Exception Filters :-Exception Filters implements IExceptionFilter interface and are used to inject logic if any exception is thrown either by controller or Action.