I got some logic I want to execute each time a action returns a view. The logic needs to know the name of the action and the controller. At the moment I am working with a filter on each controller/action but sometimes I want all the actions that return a view to use this logic. So adding filters everywhere seems like extra work I can avoid.
+1
A:
To know action and controller name from within the filter:
String ActionName = filterContext.ActionMethod.Name;
String ControllerName = filterContext.Controller.ToString();
To apply filter to all actions, define OnActionExecuting
on a base Controller class and then subclass it.
I've asked a specific question on how to only filter actions that return a view...
giorgian
2009-08-29 13:58:13
+1
A:
You can override the OnActionExecuting or OnActionExecuted method to provide common behavior for all actions in a controller. If you want it to apply to multiple controllers you can create a base controller class with this override and have those controllers that need this behavior derive from the base controller.
public override void OnActionExecuting( ActionExecutingContext filterContext )
{
... common code here ...
}
public override void OnActionExecuted( ActionExecutedContext filterContext )
{
if (filterContext.Result is ViewResult)
{
... common code here ...
}
}
tvanfosson
2009-08-29 13:58:21
Is there a way to let all the controllers derive from that base class?
Pickels
2009-08-29 14:15:52
Sure. They all derive from Controller now. Just change the base class when you create a new controller.
tvanfosson
2009-08-29 14:18:50
But what if you have a project that already has 20 controllers. Do you manually update them all or can I tell all controllers to derive from the new base controller in one location?
Pickels
2009-08-29 14:26:04
They'd have to all be updated manually, I suppose. You'd only have to write tests for the functionality on the base controller, though. Re-basing even 20 classes doesn't seem like a bad trade-off in reducing the filter decoration of all of your actions. Make sure though that it is really an action you want applied everywhere or you'll end up writing a lot of "switch" code in the base controller method to account for different scenarios. This would be a sign that you should use the filter method. I use the base controller method to inject the user's chosen theme onto the page, for example.
tvanfosson
2009-08-29 14:34:53
Okay, that's pretty clear. Thanks for taking the time to answer all my questions.
Pickels
2009-08-29 14:47:09