This article will give you understanding about Custom Action Filters in Asp.Net MVC.
When request processing is going on then I pass from different levels and sometimes it is required to pass some logic on a particular stage, then filters are used. So, basically filters are used to add some logic or injecting some logic at different levels when request is processed.
There are five types of filters with ASP.NET MVC 5 and they are as follows.
Authorization Filter: It is performing before or after the validating the request.
Action Filter: It is performing before or after action method.
Result Filter: It is performing before or after the action result.
Exception Filter: It is executed if there is some exception thrown by application when performing action process. It is used to show the error page or for logging error details.
Today, we are going to learn about only Action Filters and about rest of the filters we will cover in next article.
Action Filters
It is used to execute filter logic either before the action method execution or after the action method execution. It completes some task sometimes before the action runs or after the action run. There are several tasks which should be done before or after the action execution like logging, authentication, caching, etc.
To implement action filters, you need to create custom action filters.
Custom Action Filters
Now, you are going to create a Custom Action Filter which implements the pre-processing and post-processing logic. It will inherit from ActionFilterAttribute class and also implement IActionFilterinterface.
ActionFilterAttribute contains four important methods as in the following.
OnActionExecuting: It is called just before the action method is going to call.
OnActionExecuted: It is called just after the action method is called.
OnResultExecuting: It is called just before the result is executed; it means before rendering the view.
OnResultExecuted: It is called just after the result is executed, it means after rendering the view.
Now, it is time to add new class name as “CustomActionFilter.cs” which is inherited from ActionFilterAttribute and also implemented IActionFilter interface.
Let’s see an example of Custom Filter to check the user privilege to access the particular resource or not. See the following code.
Example 1
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Web.Routing;
namespace FilterDemo
{
public class AuthorizationPrivilegeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
AuthorizationService _authorizeService = new AuthorizationService();
string userId = HttpContext.Current.User.Identity.GetUserId();
if (userId != null)
{
var result = _authorizeService.CanManageUser(userId);
if (!result)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{{ "controller", "Account" },
{ "action", "Login" }
});
}
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{{ "controller", "Account" },
{ "action", "Login" }
});
}
base.OnActionExecuting(filterContext);
}
}
}
Example 2
public class LoggingFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
filterContext.ActionDescriptor.ActionName);
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown");
base.OnActionExecuted(filterContext);
}
}
You can see in the above code, we are overriding the OnActionExecuting method, it is because this will called before the action method executes.
There are following way to use your Custom Action Filters.
As Global Filter
You need to add your filter globally, to add your filter to the global filter. You first need to add it on Global.asax file.
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
//otehr code
AppConfig.Configure();
}
You can use FilterConfig.cs which is inside the App_Start folder and as you know, App_Start is accessible globally.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizationPrivilegeFilter());
}
}
You can add filter on controller as an attribute and filter will be applicable to all the corresponding action method.
On Controller Level
[AuthorizationPrivilegeFilter]
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
Student model = new Student() {
StudentId=10,
StudentName="Mukesh Kumar",
Address="New Delhi"
};
TempData["StudentDetail"] = model;
TempData["Message"] = "This is Sudent Details using TempData";
return RedirectToAction("Check");
}
}
On Action Level
If you add the action filter on particular action as an attribute then it will be applicable to only one of this action.
[AuthorizationPrivilegeFilter]
public ActionResult Index()
{
Student model = new Student() {
StudentId=10,
StudentName="Mukesh Kumar",
Address="New Delhi"
};
TempData["StudentDetail"] = model;
TempData["Message"] = "This is Sudent Details using TempData";
return RedirectToAction("Check");
}
Thanks for reading this article, hope you enjoyed it.