Introduction
As part of this article, we will learn about ASP.Net MVC filters, and 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
Note. 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 the AllowAnonymous attribute to allow some action method to all users.
We can also create custom Authorization filters for this we have to implement the IAuthenticationFilter interface and override 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.
[OutputCache(Duration=100)]
public ActionResult Index()
{
return View();
}
We can also create a custom action filter either by implementing the 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)




Join the conversation! Your thoughts help the community grow.