Monday, January 6, 2014

Step By Step How to create a Custom Action Filter in ASP.NET MVC 4

         By Carmel Schvartzman


In this tutorial we'll learn how to create a Custom Action Filter  in ASP.NET MVC 4. A custom Action Filter is a class which inherits from the ActionFilterAttribute class, and overrides the OnActionExecuting method (if we want the custom  Action Filter execute before the Action method) or the OnActionExecuted method  (if we want the custom  Action Filter execute after the Action method).


An Action Filter is an attribute applied to an Action method or to a Controller in order to modify its execution. If it decorates a Controller, it applies to every Action method on the Controller.

An Action Filter performs pre-action and post-action processing, in each one of the following areas:

   1) Exceptions: copes with an unhandled exception thrown inside an Action method (or the whole        Controller) using for example the HandleErrorAttribute.

   2) Actions: performing additional processing, such as checking the return value, logging, anti-image leeching, or cancelling execution, or even calling another Action methods (Dynamic Actions).

   3) Authorizations: performing authentication of the requests, using for example the AuthorizeAttribute.

   4) Results: wrapping the execution of the ActionResult , using for example the OutputCacheAttribute.

Because an Action or Controller can have several Action Filters, these have an "Order" property, to specify in which order the Filters must be executed. The first priority order is -1, and each greater integer number means a lower priority. If not specified, the order number remains -1.

We can create our own custom Action filter by inheriting from the ActionFilterAttribute class, an abstract class containing 4 virtual methods for overriding: OnResultExecuting , OnActionExecuting, OnResultExecuted, OnActionExecuted. These methods are called by the MVC engine
according to its name: before or after the method execution, and in the case of the OnResultExecuted/Executing, after or before the ActionResult is returned from the Action method.

The OnActionExecuting method gets an ActionExecutingContext which contains an "Cancel" property that can be used to cancel the Action being executed. The OnActionExecuted contains an Exception property that can be used to determine whether an  error has been thrown , and handle it.

In this Tutorial we'll create a custom Action Filter to perform logging before and after a specific Action method is called . Open Visual Studio and create a New Project, selecting ASP.NET MVC 4 Web Application:



In the next dialog, select the "Internet Application" template with "Razor" engine:


Press F5 to build and debug the app. We get the following web page:


Now for the creation of our custom Action Filter, add a class named "LogActionFilterAttribute", inheriting the ActionFilterAttribute class:


Type the inheritance settings of the class:


Now select which ActionFilterAttribute virtual method you want to override:


First method to override will be OnActionExecuting, in which we code the following expresions to write to the Trace log:


We use here the HttpContext within the received ActionExecutingContext, to write to the Tracing log, the name of the current Action method, and the date and timeץ

Next, we override the OnActionExecuted method:



We get the following bootstrap:


Now we'll use the ActionExecutedContext to log just as we did before:


Finally we decorate some Action method with our custom Action Filter, for example the "Contact" Action method:



Last but not least, we must modify the web.config file to enable tracing. Append to the system.web node the "trace" element with the following definitions:




Press F5 to build and debug the app:


And now go to the "Contact" web page:

The Contact web page is rendered:


To see the log trace, browse to the trace.axd :




In the entry corresponding to the Home/Contact page, click on View Details:


As you can see, the Action Filter has written the Messages in the trace.

To see the whole process in action, set some breakpoints and debug ( F5 ) your application:

OnActionExecuting is called before entering the Contact Action method. Next, the Contact Action method executes:



After executing the Action method, the OnActionExecuted is fired:


In this Tutorial we have applied a custom Action Filter to perform logging before and after execution of an action method.
That's all!! 
Happy programming.....


כתב: כרמל שוורצמן