Learn About Filters In ASP.NET MVC


As part of this article, we will learn about ASP.Net MVC filters, their different types and we will create a custom log Action Filter using Visual Studio. So without wasting any time let's start.

What are ASP.Net MVC filters

In an ASP.Net MVC Web application, we have action methods defined in controllers that call from different views. For example, when the user clicks on some button on the view, a request goes to the designated controller and then the corresponding action method. Within this flow, sometimes we want to perform logic either before an action method is called or after an action method runs.
To fulfill the above condition ASP.Net MVC provides us filters. Filters are the custom classes that provide us with an option to add pre-action and post-action behavior to controller action methods.
ASP.NET MVC framework supports four different types of filters:
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters
They are executed in the order listed above.

Authorization filters

In ASP.NET MVC web application by default, all the action methods of all the controllers can be accessible for all the users (for both authenticated and anonymous users both). For this, if we want to restrict some action methods from anonymous users or we want to allow the action methods only to an authenticated user, then you need to use the Authorization Filter in MVC.
The Authorization Filter provides two built-in attributes such as Authorize and AllowAnonymous. We can decorate our action methods with the Authorize attribute which allows access to the only authenticated user and we can use AllowAnonymous attribute to allow some action method to all users.
We can also create custom Authorization filters for this we have to implement IAuthenticationFilter interface and have overrides its OnAuthentication() and OnAuthenticationChallenge(). We are going deep into it.

Action filters

In the ASP.NET MVC web application, action filters are used to perform some logic before and after action methods. The output cache is one of the built-in action filters which we can use in our action methods.
  1. [OutputCache(Duration=100)]
  2. public ActionResult Index()
  3. {
  4.    return View();
  5. }
We can also create a custom action filter either by implementing IActionFilter interface and FilterAttribute class or by deriving the ActionFilterAttribute abstract class. As part of this article, I am covering creating a custom action filter using the ActionFilterAttribute abstract class.
ActionFilterAttribute includes the following method to override it:
  • void OnActionExecuted(ActionExecutedContext filterContext)
  • void OnActionExecuting(ActionExecutingContext filterContext)
  • void OnResultExecuted(ResultExecutedContext filterContext)
  • void OnResultExecuting(ResultExecutingContext filterContext)
We will see this in detail below.

Result filters

In an ASP.NET MVC web application, result filters are used to perform some logic before and after a view result is executed. For example, we might want to modify a view result right before the view is rendered.

Exception filters

In the ASP.NET MVC web application, we can use an exception filter to handle errors raised by either our controller actions or controller action results. We also can use exception filters to log errors.

Creating a Log Action Filter

Open Visual Studio and create a new ASP.NET Web Application
Learn About Filters In ASP.NET MVC
Choose Empty, select “MVC” and then click the OK button.
Learn About Filters In ASP.NET MVC
Add a ‘Filters’ folder and create a new class LogActionFilter.cs under it:
  1. using System.Diagnostics;  
  2. using System.Web.Mvc;  
  3. using System.Web.Routing;  
  5. namespace FiltersMVC.Filters  
  6. {  
  7.     public class LogActionFilter : ActionFilterAttribute  
  9.     {  
  10.         public override void OnActionExecuting(ActionExecutingContext filterContext)  
  11.         {  
  12.             Log("OnActionExecuting", filterContext.RouteData);  
  13.         }  
  15.         public override void OnActionExecuted(ActionExecutedContext filterContext)  
  16.         {  
  17.             Log("OnActionExecuted", filterContext.RouteData);  
  18.         }  
  20.         public override void OnResultExecuting(ResultExecutingContext filterContext)  
  21.         {  
  22.             Log("OnResultExecuting", filterContext.RouteData);  
  23.         }  
  25.         public override void OnResultExecuted(ResultExecutedContext filterContext)  
  26.         {  
  27.             Log("OnResultExecuted", filterContext.RouteData);  
  28.         }  
  31.         private void Log(string methodName, RouteData routeData)  
  32.         {  
  33.             var controllerName = routeData.Values["controller"];  
  34.             var actionName = routeData.Values["action"];  
  35.             var message = $"{methodName} controller:{controllerName} action:{actionName}";  
  36.             Debug.WriteLine(message, "Action Filter Log");  
  37.         }  
  38.     }  
  39. }  
We overrides OnActionExecuting(), OnActionExecuted(), OnResultExecuting(), and OnResultExecuted() methods all are calling the Log() method. The name of the method and the current route data is passed to the Log() method. The Log() method writes a message to the Visual Studio Output window.
Now, add HomeController.cs under the Controllers folder.
  1. using FiltersMVC.Filters;  
  2. using System.Web.Mvc;  
  4. namespace FiltersMVC.Controllers  
  5. {  
  6.     [LogActionFilter]  
  7.     public class HomeController : Controller  
  8.     {  
  9.         // GET: Home  
  10.         public ActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.     }  
  15. }  
After adding the above files our folder structure will look like this:
Learn About Filters In ASP.NET MVC
Now run the application, we can see the results in the “Output” window.
Learn About Filters In ASP.NET MVC
Thanks for reading this, and stay tuned for the next articles.

Similar Articles