ASP.NET MVC provides a simple way to inject your piece of code or logic either before or after an action is executed. This can be achieved by using filters and attribute classes.
Types of Filters
The ASP.NET MVC framework provides five types of filters and executes in the same order as given below,
- Authentication filters
- Authorization filters
- Action filters
- Result filters
- Exception filters
Create an action method in HomeController and declare Attribute classes Above Action Method.
- public class HomeController: Controller
-
- {
- [CustomAuthorizationAttribute]
- [CustomActionAttribute]
- [CustomResultAttribute]
- [CustomExceptionAttribute]
-
- public ActionResult Index()
- {
-
- ViewBag.Message = "Index Action of Home controller is being called.";
- return View();
- }
- }
Now, Create a Filters Folder in your application and add the following attribute classes.
- CustomAuthorizationAttribute.cs
- public class CustomAuthorizationAttribute: FilterAttribute, IAuthorizationFilter
-
- {
- void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
- {
- filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called";
- }
- }
- CustomActionAttribute.cs
- public class CustomActionAttribute: FilterAttribute, IActionFilter
- {
- void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
- {
- filterContext.Controller.ViewBag.OnActionExecuting = "IActionFilter.OnActionExecuting filter called";
- }
- void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
- {
- filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called";
- }
- }
- CustomResultAttribute.cs
- public class CustomResultAttribute: FilterAttribute, IResultFilter
- {
- void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
- {
- filterContext.Controller.ViewBag.OnResultExecuting = "IResultFilter.OnResultExecuting filter called";
- }
- void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
- {
- filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called";
- }
- }
- CustomExceptionAttribute.cs
- public class CustomExceptionAttribute: FilterAttribute, IExceptionFilter
- {
- void IExceptionFilter.OnException(ExceptionContext filterContext)
- {
- filterContext.Controller.ViewBag.OnException = "IExceptionFilter.OnException filter called";
- }
- }
View
Index.cshtml
- @{
- ViewBag.Title = "Index";
- }
- <h2>
- Index</h2>
- <ul>
- <li>@ViewBag.OnAuthorization</li>
- <li>@ViewBag.OnActionExecuting</li>
- <li>@ViewBag.OnActionExecuted</li>
- <li>@ViewBag.OnResultExecuting</li>
- <li>@ViewBag.OnResultExecuted</li>
- <li>@ViewBag.Message</li>
- </ul>
Here is the Output.