ASP.NET MVC Filters

In ASP.NET MVC controllers define action methods, which usually have a one-to-one relationship with possible user interactions, but sometimes you need to execute logic either before calling the action method or after running the action method.

To support this ASP.NET MVC provides filters. Filters are user-defined classes that provide both declarative and programmatic tools for adding pre-and post-action behaviors to controller action methods.

Action Filters

An action filter is an attribute that you can apply to a controller action or to the entire controller, which changes how the action is performed. The ASP. NET MVC Framework includes several action filters —

  • OutputCache-caches the output of a controller action for the specified time interval.
  • HandleError-Handles errors that occur when performing a controller action.
  • Authorization-allows you to restrict access to a specific user or role.

OutputCache-caches the output of a controller action for the specified time interval.

HandleError-Handles errors that occur when performing a controller action.

Authorization-allows you to restrict access to a specific user or role.

Types of filters

Platform ASP.NET MVC supports four different types of filters:

  • Authorization Filters-implements the IAuthorizationFilter attribute.
  • Action Filters-implements the IActionFilter attribute.
  • Result Filters-implements the IResultFilter attribute.
  • Exception Filters-implements the IExceptionFilter attribute.

Authorization Filters-implements the IAuthorizationFilter attribute.

Action Filters-implements the IActionFilter attribute.

Result Filters-implements the IResultFilter attribute.

Exception Filters-implements the IExceptionFilter attribute.

Filters are executed in the order specified above. For example, authorization filters are always executed before action filters, and exception filters are always executed after every other filter type.

Authorization filters are used to implement authentication and authorization for controller actions. For example, an authorization filter is an example of an authorization filter.

Let’s look at a simple example by creating a new project ASP.Net MVC.

Step 1-Open Visual Studio and select “File” → ” New ” → “Project” menu item.

A new project dialog box opens

Step 2-In the left pane, select Templates → Visual C # → The Internet.

Step 3-In the middle panel, select the Web application ASP.NET.

Step 4. Enter the project name MVCFiltersDemo in the Name field and click OK to continue, and you will see the following dialog box asking you to set the initial content for the project ASP.NET.

Step 5. To simplify the task, select the “Clear” option and check the MVC box under “Add folders and main links for” and click OK.

This will create a basic MVC project with minimal predefined content.

Step 6. To add a controller, right-click the controller folder in the Solution Explorer and select Add – > Controller.

The Add Scaffold dialog box appears.

Step 7-Select MVC 5 Controller-Empty option and click”Add”.

The Add Controller dialog box opens.

Step 8-Set the HomeController name and click”Add”.

You will see a new C # file “HomeController. cs “in the” Controllers ” folder, which is also open for editing in Visual Studio.

Apply Action Filter

The action filter can be applied either to a single controller action or to the entire controller. For example, the OutputCache action filter is applied to an action named Index () that returns a string. This filter causes the value returned by the action to be cached for 15 seconds.

To make this a working example, let’s change the controller class by changing the action method named Index using the following code.

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers {
   public class HomeController : Controller{
      // GET: Home
      [OutputCache(Duration = 15)]
		
      public string Index(){
         return "This is ASP.Net MVC Filters Tutorial";
      }
   }
}

When you launch this app, you will see that the browser displays the result of the Index action method.

Let’s add another action method that will display the current time.

namespace MVCFiltersDemo.Controllers{
   public class HomeController : Controller{
      // GET: Home
		
      [OutputCache(Duration = 15)]
      public string Index(){
         return "This is ASP.Net MVC Filters Tutorial";
      }
		
      [OutputCache(Duration = 20)]
      public string GetCurrentTime(){
         return DateTime.Now.ToString("T");
      }
   }
}

Request the following URL, http: / / localhost: 62833 / Home / getCurrentTime, and you will get the following output.

f you refresh your browser, you will see the same time because the action is cached for 20 seconds. It will be updated when you update it in 20 seconds.

Custom Filters

To create your own custom filter platform ASP.NET MVC provides a base class called ActionFilterAttribute. This class implements the IActionFilter and IResultFilter interfaces, and both are derived from the Filter class.

Let’s look at a simple example of a custom filter by creating a new folder in your project using ActionFilters. Add one class, for which right-click the ActionFilters folder and select ” Add ” → “Class”.

Enter “MyLogActionFilter”in the name field and click Add.

This class will derive from ActionFilterAttribute, which is the base class and overrides the following method. The full implementation of MyLogActionFilter is shown below.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCFiltersDemo.ActionFilters {
   public class MyLogActionFilter : ActionFilterAttribute{
      public override void OnActionExecuting(ActionExecutingContext filterContext){
         Log("OnActionExecuting", filterContext.RouteData);
      }
		
      public override void OnActionExecuted(ActionExecutedContext filterContext){
         Log("OnActionExecuted", filterContext.RouteData);
      }
		
      public override void OnResultExecuting(ResultExecutingContext filterContext){
         Log("OnResultExecuting", filterContext.RouteData);
      }
		
      public override void OnResultExecuted(ResultExecutedContext filterContext){
         Log("OnResultExecuted", filterContext.RouteData);
      }
		
      private void Log(string methodName, RouteData routeData){
         var controllerName = routeData.Values["controller"];
         var actionName = routeData.Values["action"];
			
         var message = String.Format(
            "{0} controller:{1} action:{2}", methodName, controllerName, actionName);
				
         Debug.WriteLine(message, "Action Filter Log");
      }
   }
}

Let’s now apply the log filter to HomeController using the following code.

using MVCFiltersDemo.ActionFilters;
using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers {
   [MyLogActionFilter]
   public class HomeController : Controller{
      // GET: Home
		
      [OutputCache(Duration = 10)]
      public string Index(){
         return "This is ASP.Net MVC Filters Tutorial";
      }
		
      [OutputCache(Duration = 10)]
      public string GetCurrentTime(){
         return DateTime.Now.ToString("T");
      }
   }
}

Launch the app and then view the output window.

As you can see in the screenshot above, the action processing steps are recorded in the Visual Studio output window.

Leave a Reply

Your email address will not be published.

You May Also Like
Read More

Web projects

So far, we’ve only covered how you can create websites without any project files. The advantage of project-free development…