| || |
Action Filter in ASP.NET MVC Applications
Posted On: 10-Jan-2016 09:20
In this article we will try to see what are action filters, how we can use it and how we can create own custom action filters in an ASP.NET MVC application. Action filters are attributes that you can put on Action or entire controller. Action filters are an excellent way of injecting extra processing logic into the MVC pipeline. We will try to understand action filters and how to create custom action filter.
What are Action Filters
Action filters are attributes that you can put on Action or entire controller. Action filters modify the way in which Action executing. MVC provides different inbuilt Action Filter as
You can also create you own Action Filter. For suppose you want to create custom authentication system or log the user activity or going to modify the response content (minify the response contents) etc. In all cases you can create you custom Action Filter.
How to create Custom Action Filter
For create a new custom Filter you need to know different type of Action Filters:
Filters are executed in the order listed above.The base class of action filters is the System.Web.Mvc.FilterAttribute. If you want to implement a filter, then you need to create a class that inherits from the FilterAttribute class and implements one or more of the IAuthenticationFilter, IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces.
Now, we are going to create custom action filter, purpose is just passing a message to View. To do this, I have created a class and extended the AuthorizeAttribute class as:
public class CustAuthFilter : AuthorizeAttribute
public override void OnAuthorization(AuthorizationContext filterContext)
filterContext.Controller.ViewBag.AutherizationMessage ="Custom Authorization: Message from OnAuthorization method.";
In Controller code:
public class HomeController : Controller
ViewBag.Title ="Home Page";
<h2>Output Messages :</h2>
In the above discusion we try to understand what are action filters and how to create custom action filters. I hope it will help you.
Active User (2)