Sunday, 17 November 2013

Action selectors and action filters in ASP.Net MVC

At the time of writing MVC is in version 5.0.

Firstly, the details of what an action is are outside the scope of this post but in essence an action is a public method on a controller class that the framework invokes in response to an incoming request. 

Action selectors

Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request.

For example the ActionName attribute can be used to change the name to invoke an action method. In the following code snippet the Index() action method will be invoked with the name “List” rather than “Index” in the URL. In fact “Index” would be invalid. Note also that the view, if there is one, must also be called “List” and not “Index” unless you use an overloaded version of the View() method that takes the name of a view as a parameter.

[ActionName("List")]
public ActionResult Index()
{
    return View("Index");
}

 

The ActionVerbs selector is used when we want to control the selection of the action method based on request type. For example you can define which method responds to an HTTP Get and which responds to an HTTP Post. For example:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
    return View();
}

 

Note that there are some shortcut attributes that do the same thing: [HttpGet] and [HttpPost]. See the previous post Why use the MVC AcceptVerbs attribute?

 

Action filters

Action filters apply pre and post processing logic to an action method and can modify the result. Action filters are typically used to apply cross-cutting concerns, logic that you want to apply to multiple methods but don’t want to duplicate code across controllers. Caching, validation and authorisation are examples of the type of cross-cutting concerns that action filters can be used to implement.

Action filters can be applied to individual methods or to the controller itself. When applied at the controller level the filter will apply to all action methods in that controller.

In ASP.NET MVC there are basically 4 different types of filter:

  • Authorization filters – Implements the IAuthorizationFilter attribute.
  • Action filters – Implements the IActionFilter attribute.
  • Result filters – Implements the IResultFilter attribute.
  • Exception filters – Implements the IExceptionFilter attribute.

 

public class HomeController : Controller
{
    [OutputCache(Duration=10)]
    public string Index()
    {
         return View();
    }
}

 

See Filtering in ASP.NET MVC.

A note about global filters

Filters can be applied globally, that is to every request that is processed by any controller in your application. You can register global filters in the FilterConfig class located under the App_Start folder of your MVC project.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

 

Applying a global filter might be a good way of implementing logging. Simply create a new filter attribute that extends ActionFilterAttribute and register it in FilterConfig. Note that there is a default location for filters in the MVC application template – under the Filters folder.

public class LogAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Do logging here
        base.OnActionExecuted(filterContext);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Do logging here
        base.OnActionExecuting(filterContext);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        // Do logging here
        base.OnResultExecuted(filterContext);
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        // Do logging here
        base.OnResultExecuting(filterContext);
    }
}

 

Summary

  • Action selectors are implemented as attributes and influence what action methods are selected for invocation in response to an incoming request.
  • Action filters allow pre and post processing logic to be applied to an action method.