Filters and attributes are ways of creating re-usable bits of code that you can use with attributes to methods in your controllers. You can also apply the annotation to the whole controller to apply the code logic to ALL of the methods in the controller class.
Here is the simplest implementation of custom attributes that I came up with. Put this in one of your controllers, or set up another class file for all of your attributes.
public class CustomActionAttribute : FilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{ context.Controller.ViewBag.OnActionExecutedViewBag = "IActionFilter.OnActionExecuted filter called";
}
void IActionFilter.OnActionExecuting(ActionExecutingContext context)
{ context.Controller.ViewBag.OnActionExecutingViewBag = "IActionFilter.OnActionExecuting filter called";
}
}
As long as you add the IActionFilter attribute, visual studio error will give you enough information to build the methods. i.e. you must implement OnActionExecuted and OnActionExecuting. Errors are thrown if the parameters are missing as well.
Add the annotation to a controller class (or to the whole controller):
[CustomAction]
public ActionResult Index()
{
return View();
}
This code in your view should convince you that the code executed:
@ViewBag.OnActionExecutingViewBag
@ViewBag.OnActionExecutedViewBag
If you want to add parameters [CustomAction(Message="Description for attribute")]
, just add properties to your class:
public class CustomActionAttribute : FilterAttribute, IActionFilter
{
public string Message { get; set; }
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
if (!string.IsNullOrEmpty(Message)) context.Controller.ViewBag.OnActionExecutedViewBag = Message;
else
context.Controller.ViewBag.OnActionExecutedViewBag = "IActionFilter.OnActionExecuted filter called 2";
}
You can use the following types of filters, similarly to the way we implemented the Action filter:
- Authorization filter
- Action filter
- Result filter
- Exception filter