Action Filter is an attribute that when added to an action of a controller, change the way their action is performed.
Action Filter HandleError is used to redirect to a custom error page when an error is triggered by the action of the controller.
Listing 1: HandleError example
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
throw new NullReferenceException();
}
public ActionResult About()
{
return View();
}
}
When the NullReferenceException error happens in the action Index, the ASP.NET will find in a view called “Error”, in the controller views folder and renders it to the user. When the view called “Error” stay in the “Shared” Folder, will be shared with all controllers application.
We can also, redirect to the error pages, each type of error:
Listing 2: Redirect example
[HandleError(ExceptionType = typeof(NullReferenceException),
View = "NullError")]
[HandleError(ExceptionType = typeof(SecurityException),
View = "SecurityError")]
public class HomeController : Controller
{
public ActionResult Index()
{
throw new NullReferenceException();
}
public ActionResult About()
{
return View();
}
}
This Action Filter is one of the most importants, because is used to define the guidelines of the application security, with him is possible to define how many users or groups of users will have access to specific controller actions.
Listing 3: Only logged users can join in the action About()
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult About()
{
return View();
}
}
Is also possible define a security system based on users groups:
Listing 4: Only users from Admin and Funcionarios group have access to the action About()
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize(Roles="Admin, Funcionarios")]
public ActionResult About()
{
return View();
}
}
Listing 5: Only Pedro and Olga can access the action About()
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize(Users = "Pedro, Olga")]
public ActionResult About()
{
return View();
}
}
This ActionFilter enables the cache of controller actions, useful when specific pages don't change very often and makes it unnecessary to make the whole process several times.
Listing 6: OutputCache example with 15 seconds of duration
public class HomeController : Controller
{
[OutputCache(Duration = 15)]
public ActionResult Index()
{
return DateTime.Now;
}
public ActionResult About()
{
return View();
}
}
When the action above is called, the screen will show the current time, and in about 15 seconds you’ll see the same date and hour, because the action result was placed in the cache and is reused instead of calling the action again, if this Action Filter is used correctly, can have a significant improvement in application performance.

See the prices for this post in Mr.Bool Credits System below: