Wednesday, April 1, 2015

Filtering in ASP.NET MVC

In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with possible user interactions, such as clicking a link or submitting a form. For example, when the user clicks a link, a request is routed to the designated controller, and the corresponding action method is called.
Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.
A Visual Studio project with source code is available to accompany this topic: Download.

ASP.NET MVC Filter Types


ASP.NET MVC supports the following types of action filters:
The Controller class implements each of the filter interfaces. You can implement any of the filters for a specific controller by overriding the controller's On<Filter> method. For example, you can override the OnAuthorization method. The simple controller included in the downloadable sample overrides each of the filters and writes out diagnostic information when each filter runs. You can implement the following On<Filter> methods in a controller:

Filters Provided in ASP.NET MVC


ASP.NET MVC includes the following filters, which are implemented as attributes. The filters can be applied at the action method, controller, or application level.
  • AuthorizeAttribute. Restricts access by authentication and optionally authorization.
  • HandleErrorAttribute. Specifies how to handle an exception that is thrown by an action method.
    NoteNote:
    This filter does not catch exceptions unless the customErrors element is enabled in the Web.config file.
  • OutputCacheAttribute. Provides output caching.
  • RequireHttpsAttribute. Forces unsecured HTTP requests to be resent over HTTPS.

How To Create a Filter


You can create a filter in the following ways:
  • Override one or more of the controller's On<Filter> methods.
  • Create an attribute class that derives from ActionFilterAttribute and apply the attribute to a controller or an action method.
  • Register a filter with the filter provider (the FilterProviders class).
  • Register a global filter using the GlobalFilterCollection class.
A filter can implement the abstract ActionFilterAttribute class. Some filters, such as AuthorizeAttribute, implement the FilterAttribute class directly. Authorization filters are always called before the action method runs and called before all other filter types. Other action filters, such as OutputCacheAttribute, implement the abstractActionFilterAttribute class, which enables the action filter to run either before or after the action method runs.
You can use the filter attribute declaratively with action methods or controllers. If the attribute marks a controller, the action filter applies to all action methods in that controller.
The following example shows the default implementation of the HomeController class. In the example, the HandleError attribute is used to mark the controller. Therefore, the filter applies to all action methods in the controller.
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}


Filter Providers


Multiple filter providers can be registered. Filter providers are registered using the static Providers property. The GetFilters(ControllerContext, ActionDescriptor) method aggregates the filters from all of the providers into a single list. Providers can be registered in any order; the order they are registered has no impact on the order in which the filter run.
NoteNote:
Filter providers are a new feature to ASP.NET MVC 3.
By default, ASP.NET MVC registers the following filter providers:
The GetFilters method returns all of the IFilterProvider instances in the service locator.

Filter Order


Filters run in the following order:
  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters
For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, theScope enumeration value specifies the order for filters. This enumeration defines the following filter scope values (in the order in which they run):
For example, an OnActionExecuting(ActionExecutingContext) filter that has the Order property set to zero and filter scope set to First runs before an action filter that has theOrder property set to zero and filter scope set to Action. Because exception filters run in reverse order, an exception filter that has the Order property set to zero and filter scope set to First runs after an action filter that has the Order property set to zero and filter scope set to Action.
The execution order of filters that have the same type, order, and scope is undefined.
NoteNote:
In ASP.NET MVC version 3, the order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller with the same Order value as those on an action method were executed before the exception filters on the action method. This would typically be the case if exception filters are applied without a specified Order value. In ASP.NET MVC 3, this order has been reversed so that the most specific exception handler executes first. For more information, see the filter order section later in this document.

Canceling Filter Execution


You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value. Any pending OnActionExecutedand OnActionExecuting filters will not be invoked and the invoker will not call the OnActionExecuted method for the canceled filter or for pending filters. The OnActionExecutedfilter for previously run filters will run. All of the OnResultExecutingand OnResultExecuted filters will run.
For example, imagine an ASP.NET MVC application that has a home controller and a simple controller. A global request timing filter is applied to the application. The request timing filter implements the four action and result filters (OnActionExecutingOnActionExecutedOnResultExecuting and OnResultExecuted). Each filter method in the application writes trace information with the name of the filter, the name of the controller, the name of the action and the type of the filter. In that case, the filter type is a request timing filter. A request to the Index action of the Home controller shows the following output in the trace listener (debug window).
Filter Method
Controller
Action
Filter type
OnActionExecuting
Home
Index
Request timing filter
OnActionExecuted
Home
Index
Request timing filter
OnResultExecuting
Home
Index
Request timing filter
OnResultExecuted
Home
Index
Request timing filter
Consider the same application where a trace action filter is applied to the simple controller. The simple controller also implements the four action and result filters. The simple controller has three filters, each of which implements the four action and result methods. A request to the Details action of the Simple controller shows the following output in the trace listener:
Filter Method
Controller
Action
Filter type
OnActionExecuting
Simple
Details
Simple Controller
OnActionExecuting
Simple
Details
Trace action
OnActionExecuting
Simple
Details
Request timing
OnActionExecuted
Simple
Details
Request timing
OnActionExecuted
Simple
Details
Trace action
OnActionExecuted
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Trace action
OnResultExecuting
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Trace action
OnResultExecuted
Simple
Details
Simple Controller
Now consider the same application where the trace action filter sets the result property to "Home/Index", as shown in the following example:
if (filterContext.RouteData.Values.ContainsValue("Cancel")) {
    filterContext.Result = new RedirectResult("~/Home/Index");
    Trace.WriteLine(" Redirecting from Simple filter to /Home/Index");
}
The request to the Details action of the Simple controller with the canceled result shows the following output in the trace listener:
Filter Method
Controller
Action
Filter type
OnActionExecuting
Simple
Details
Simple Controller
OnActionExecuting
Simple
Details
Trace action
OnActionExecuted
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Trace action
OnResultExecuting
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Trace action
OnResultExecuted
Simple
Details
Simple Controller
OnActionExecuting
Home
Index
Request timing filter
OnActionExecuted
Home
Index
Request timing filter
OnResultExecuting
Home
Index
Request timing filter
OnResultExecuted
Home
Index
Request timing filter
The downloadable sample for this topic implements the filtering described in these tables.

Filter State


Do not store filter state in a filter instance. Per-request state would typically be stored in the Items property. This collection is initialized to empty for every request and is disposed when the request completes. Transient per-user state is typically stored in the user's session. User-state information is often stored in a database. The downloadable sample for this topic includes a timing filter that uses per-request state. For information about how to create stateful filters, see the video Advanced MVC 3.

Related Topics


Title
Description
(Blog entry) Describes ASP.NET MVC filters in a service location context.
Describes how to use the Authorize attribute to control access to an action method.
Describes how to use the OutputCache attribute to provide output caching for an action method.
Describes how to use the HandleError attribute to handle exceptions that are thrown by an action method.
Describes how to implement custom action filters.
Explains how to add a custom action filter to an ASP.NET MVC application.

Creating Custom Action Filters

The possible uses for action filters are as varied as the actions to which they can be applied. Some possible uses for action filters include the following:
  • Logging in order to track user interactions.
  • "Anti-image-leeching" to prevent images from being loaded in pages that are not on your site.
  • Web crawler filtering to change application behavior based on the browser user agent.
  • Localization to set the locale.
  • Dynamic actions to inject an action into a controller.

Implementing a Custom Action Filter

An action filter is implemented as an attribute class that inherits from ActionFilterAttributeActionFilterAttribute is an abstract class that has four virtual methods that you can override: OnActionExecutingOnActionExecutedOnResultExecuting, and OnResultExecuted. To implement an action filter, you must override at least one of these methods.
The ASP.NET MVC framework will call the OnActionExecuting method of your action filter before it calls any action method that is marked with your action filter attribute. Similarly, the framework will call the OnActionExecuted method after the action method has finished.
The OnResultExecuting method is called just before the ActionResult instance that is returned by your action is invoked. The OnResultExecuted method is called just after the result is executed. These methods are useful for performing actions such as logging, output caching, and so forth.
The following example shows a simple action filter that logs trace messages before and after an action method is called.
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);
    }
}


Action Filter Context

Each of the controller event handlers for action filtering takes a context object as a parameter. The following list shows the filter event handlers and the context type that each takes.
All context classes inherit from the ControllerContext class and include an ActionDescriptor property. You can use the ActionDescriptor property to identify which action the filter is currently applied to.
The ActionExecutingContext and ResultExecutingContext classes contain a Cancel property that enables you to cancel the action.
The ActionExecutedContent and ResultExecutedContext classes contain an Exception property and an ExceptionHandled property. If the Exception property is null, it indicates that no error occurred when the action method ran. If the Exception property is not null and the filter knows how to handle the exception, the filter can handle the exception and then signal that it has done so by setting the ExceptionHandled property to true. Even if the ExceptionHandled property is true, the OnActionExecuted orOnResultExecuted method of any additional action filters in the stack will be called and exception information will be passed to them. This enables scenarios such as letting a logging filter log an exception even though the exception has been handled. In general, an action filter should not handle an exception unless the error is specific to that filter.

Marking an Action Method with a Filter Attribute

You can apply an action filter to as many action methods as you need. The following example shows a controller that contains action methods that are marked with an action-filter attribute. In this case, all the action methods in the controller will invoke the same action filter.
[HandleError]
public class HomeController : Controller
{
    [LoggingFilter]
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        if (TempData.ContainsKey("Clicked"))
        {
            ViewData["Clicked"] = true;
        }
        else ViewData["Clicked"] = false;

        if ((Boolean)ViewData["Clicked"] == true)
        {
            ViewData["ClickMessage"] = "You clicked this button.";
            ViewData["Clicked"] = false;
        }

        return View();
    }

    [LoggingFilter]
    public ActionResult About()
    {
        return View();
    }

    [LoggingFilter]
    public ActionResult ClickMe()
    {
        TempData["Clicked"] = true;

        return RedirectToAction("Index");
    }
}


Executing Code Before and After an Action from Within a Controller

The ASP.NET MVC Controller class defines OnActionExecuting and OnActionExecuted methods that you can override. When you override one or both of these methods, your logic will execute before or after all action methods of that controller. This functionality is like action filters, but the methods are controller-scoped.
The following example shows controller-level OnActionExecuting and OnActionExecuted methods that apply to all action methods in the controller.
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        if (TempData.ContainsKey("Clicked"))
        {
            ViewData["Clicked"] = true;
        }
        else ViewData["Clicked"] = false;

        if ((Boolean)ViewData["Clicked"] == true)
        {
            ViewData["ClickMessage"] = "You clicked this button.";
            ViewData["Clicked"] = false;
        }

        return View();
    }

    public ActionResult About()
    {
        ViewData["Title"] = "About Page";

        return View();
    }

     public ActionResult ClickMe()
    {
        TempData["Clicked"] = true;

        return RedirectToAction("Index");
    }

    [NonAction]
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Trace.Write("(Controller)Action Executing: " +
            filterContext.ActionDescriptor.ActionName);

        base.OnActionExecuting(filterContext);
    }

    [NonAction]
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Exception != null)
            filterContext.HttpContext.Trace.Write("(Controller)Exception thrown");

        base.OnActionExecuted(filterContext);
    }
}


Scope of Action Filters

In addition to marking individual action methods with an action filter, you can mark a controller class as a whole with an action filter. In that case, the filter applies to all action methods of that controller.
Additionally, if your controller derives from another controller, the base controller might have its own action-filter attributes. Likewise, if your controller overrides an action method from a base controller, the method might have its own action-filter attributes and those it inherits from the overridden action method.
To make it easier to understand how action filters work together, action methods are grouped into scopes. A scope defines where the attribute applies, such as whether it marks a class or a method, and whether it marks a base class or a derived class.

Order of Execution for Action Filters

Each action filter has an Order property, which is used to determine the order that filters are executed in the scope of the filter. The Order property takes an integer value that must be 0 (default) or greater (with one exception). Omitting the Order property gives the filter an order value of -1, which indicates an unspecified order. Any action filters in a scope whose Order property is set to -1 will be executed in an undetermined order, but before the filters that have a specified order.
When an Order property of a filter is specified, it must be set to a unique value in a scope. If two or more action filters in a scope have the same Order property value, an exception is thrown.
Action filters are executed in an order that meets the following constraints. If more than one ordering fulfills all these constraints, ordering is undetermined.
  1. The implementation of the OnActionExecuting and OnActionExecuted methods on the controller always go first. For more information, see Executing Code Before and After an Action from Within a Controller.
  2. Unless the Order property is set explicitly, an action filter has an implied order of -1.
  3. If the Order property of multiple action filters are explicitly set, the filter with the lowest value executes before those with greater values, as shown in the following example:
    <Filter1(Order = 2)> _ 
    <Filter2(Order = 3)> _ 
    <Filter3(Order = 1)> _ 
    Public Sub Index()
        View("Index")
    End Sub
    
    [Filter1(Order = 2)]
    [Filter2(Order = 3)]
    [Filter3(Order = 1)]
    public void Index()
    {
        View("Index");
    }
    
    In this example, action filters would execute in the following order: Filter3Filter1, and then Filter2.
  4. If two action filters have the same Order property value, and if one action filter is defined on a type and the other action filter is defined on a method, the action filter defined on the type executes first. The following example shows two an action filter defined on the type and another defined on a method.
    <FilterType(Order = 1)> _ 
    Public Class MyController
        <FilterMethod(Order = 1)> _ 
        Public  Sub Index()
            View("Index")
        End Sub
    End Class
    
    [FilterType(Order = 1)]
    public class MyController
    {
        [FilterMethod(Order = 1)]
        public void Index()
        {
            View("Index");
        }
    }
    
    In this example, FilterType executes before FilterMethod.

1 comment: