by Paul Stovell via Paul Stovell on 12/7/2009 1:33:21 PM
Back to: Magellan Home
Action Filters are typically attributes that you can apply to a Magellan controller or controller action in order to intercept the call and provide an alternative way of handling the request. They provide a poor man's Aspect Oriented Programming mechanism for controllers.
The sample below shows how an Action Filter might be used. The Log attribute can be applied to either methods or classes:
public class MyController : Controller { [Log] public ActionResult Show(int customerId) { ... } }
The Log action filter attribute might be implemented as follows:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class LogAttribute : Attribute, IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine("Entering: {0}({1})", context.Request.Action, string.Join(", ", context.Request.ActionParameters.Select(x => x.Key + "=" + x.Value).ToArray()) ); } public void OnActionExecuted(ActionExecutedContext context) { Console.WriteLine("Exiting: {0}({1})", context.Request.Action, string.Join(", ", context.Request.ActionParameters.Select(x => x.Key + "=" + x.Value).ToArray()) ); } }
As you can see above, action filters have two hooks - before the action is invoked, and after the action is invoked. Before the action, you can:
Result
After the action, you can:
Magellan also supports Result Filters via the IResultFilter interface. These are invoked after the action has been executed, and before the result is handled. These give you the ability to handle exceptions caused when rendering the view (rather than just when processing the action).
IResultFilter
The logging example above could be extended to support Result Filters:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class LogAttribute : Attribute, IActionFilter, IResultFilter { // Other code here public void OnResultExecuting(ResultExecutingContext context) { Console.WriteLine("Rendering: {0}({1})", context.Request.Action, string.Join(", ", context.Request.ActionParameters.Select(x => x.Key + "=" + x.Value).ToArray()) ); } public void OnResultExecuted(ResultExecutedContext context) { Console.WriteLine("Rendered: {0}({1})", context.Request.Action, string.Join(", ", context.Request.ActionParameters.Select(x => x.Key + "=" + x.Value).ToArray()) ); } }
Here are some useful ways to use Action and View Filters:
Original Post: Magellan Action Filters
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.