Saturday, January 4, 2014

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

         By Carmel Schvartzman


In this tutorial we'll learn how to create an Action Filter  in ASP.NET MVC 4. 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.

The 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.

In this Tutorial we'll apply two Action Filters to action methods: the OutputCacheAttribute and the HandleErrorAttribute. 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:



The first Action Filter we'll add is an OutputCache filter. The OutputCache allows us to persist the rendered html or xml or json from an Action method in the web server RAM memory , therefore for the assigned "Duration" time of the cache , the requests will get the sane identical response, no need to rebuild the entire response. In case the Controller was decorated with an OutputCache attibute, all the Actions responses will be cached.
We'll add the  OutputCache attibute to the Index action, with a Duration of 5 seconds and a priority of -1 .Also, we'll add a timestamp to see how the OutputCacheAttribute works. Go to the Home Controller and find the "Index" Action method:



We'll use the OutputCache Attribute as follows:



Modify the code to output a timestamp:


Press F5 to build and debug the app:


We get the time when the web page was cached. Refresh repeatedly the page and you'll see that for 5 seconds the time won't update: that means the same response was rendered from the web service.

Now let's try another Action Filter: the HandleErrorAttribute. Go to the Controller and set another Action filter for the "About" Action method, but with a priority of 0. This HandleError Action Filter will handle every HttpResponseException and redirect the user to an special View that we'll call "CustomErrorView":



Code the "Throw" block to start our testings:


And also create a new View in the Views folder:



This View will just contain a  "CustomErrorView" header ; but of course you'll express here any messages or instruccions for the user:



Next, open the Web.config file and add the "CustomErrors" node to System.web, with an attribute "mode" set to "on":


Rebuild ( F6 ) your project and browse to the "Home" web page, and there click on the "About" menu link:



The user will be redirected to the CustomErrorView web page, because there was an exception throwed inside the "About" Action method, and the Action Filter handled it:




In this Tutorial we have applied two Action Filters to two action methods: the OutputCacheAttribute and the HandleErrorAttribute.
That's all!! 
Happy programming.....


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