ASP.NET MVC QuickStart 7: action filters

…continued from part 6.

Objectives

In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:

  • Task 1: understand action filters
  • Task 2: built-in action filters
  • Task 3: write a custom action filter

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 6 code.

Task 1: understand action filters

An action filter is behavior that can be attached to controllers and action methods. They inject extra logic in the request processing pipeline:

  • before and after an action method runs
  • before and after action results are executed
  • during exception handling

Action filters are very powerful if you want to inject general-purpose code that has to be reused all over the place, but implemented once, such as logging, authorization, caching and others.

The MVC framework knows about following filter types:

Filter type           Interface             When run                         
Authorization filter IAuthorizationFilter Before running any other
filter or action method
Action Filter IActionFilter Before and after an action
method is run
Result Filter IResultFilter Before and after an action
result is executed
Exception filter IExceptionFilter Handles exception thrown
by action filter, action
result or action method

The default implementations of these filter types are:

Filter type               Default implementation
Authorization filter AuthorizeAttribute
Action Filter ActionFilterAttribute
Result Filter ActionFilterAttribute
Exception filter HandleErrorAttribute

Task 2: built-in action filters

ASP.NET MVC has a number of built in action filters. To use them, you just need to decorate the controller or action filter with a specific action filter attribute, for example:

[Authorize()]
[OutputCache(Duration=60)]
public ActionResult Index()
{
…
}

In this particular example, we use the AuthorizeAttribute to specify that the Index action method can only be executed if the user is logged in. We have also decorated the action method Index with the OutputCacheAttribute, which will cache the output of the action method for a specific duration (60 seconds). These two action filters are filters that are already built-in into the ASP.NET MVC framework, but of course you can build your own action filters. Other built in action filters are: AcceptVerbs, Bind, HandleError, ModelBinder, NonAction and others.

Task 3: write a custom action filter

In this task we will create a custom action filter that logs the stages of a request to a controller action. To keep things simple, we will just write to the Visual Studio output window.

To start, add a new folder to the MvcApplication1 web application and call it ActionFilters. Right click this folder and select Add -> Class, and name it LogAttribute, and implement it with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Diagnostics;
namespace MvcApplication1.ActionFilters
{
public class LogAttribute : ActionFilterAttribute,
IActionFilter, IResultFilter, IExceptionFilter
{
#region IActionFilter Members
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
}
#endregion
#region IResultFilter Members
void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}
void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
#endregion
#region IExceptionFilter Members
public void OnException(ExceptionContext filterContext)
{
Log("OnException", filterContext.RouteData);
}
#endregion
#region Log
public static void Log(string message, RouteData routeData)
{
Trace.WriteLine(
string.Format("{0}, controller = {1}, action = {2}",
message,
routeData.Values["controller"],
routeData.Values["action"]));
}
#endregion
}
}

This code is very straightforward, notice the following:

  • the LogAttribute class inherits from ActionFilterAttribute, which provides you with the default implementation.
  • the LogAttribute class implements three interfaces: IActionFilter, IResultFilter and IExceptionFilter.
  • In each interface method the filter context is passed, that can be used to determine information about the context of where the method was triggered (controller, action method…).

Then add the following using statement on top of the MembersController:

using MvcApplication1.ActionFilters;

Now you can apply the Log action filter, for example, decorate the action method Index of the MembersController with it:

[Log]
public ActionResult Index()
{
// Get a list of members using the model
List<Member> members = MemberService.GetMembers();

// return this list to the default view
return View(members);
}

Hit F5 to start the web application, go to http://localhost:3382/members and have a look at the output window in visual studio:

Output window

As you see, the various steps in the pipeline have been written to the output window.

Note: if you would throw an exception in the Index action method, the OnException step would be executed too.

Go to next part.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.