11 Aug 2010

ASP.NET MVC 2 Controller - Use Custom Attribute to intercept call to Action

I was thinking that it would be good to have certain MVC Actions run some common code every time they are called. Naturally we could just call a common method on the first line of our Action methods, but that would not be MVC sexeh. After all, we use special Attributes such as [Authorize] and [HttpPost] to intercept the Action, so why not roll our own?

Microsoft have done the hard work for you - all you have to do is extend an attribute called ActionFilterAttribute (a type of FilterAttribute) and override its calls to the following events as required:

- OnActionExecuting
- OnActionExecuted
- OnResultExecuting
- OnResultExecuted

For example, I wanted to update the User's LastActivity timestamp whenever certain Actions were called, so I created the following:


public class LogUserActivityAttribute: ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
... Do your log activity stuff here ...

base.OnActionExecuted(filterContext);
}
}


I could then have that code executed on a per-Action basis like so...


[HttpPost]
[LogUserActivity]
public ActionResult DeleteItem(int id)
{
...
}


HTH! Incidentally, don't forget that instead of this funky MVC apprioach, you can set the Application_BeginRequest method in the global.asax file, which runs at the start of every web request to the application, e.g.

protected void Application_BeginRequest(Object sender, EventArgs e)
{
... Do your per-request stuff here ...
}

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!