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.