ActionFilter in ASP.NET MVC - OnActionExecuted
OnActionExecuted method in an action filter will be run after the controller action it is filtering is executed. The context object that gets passed in of type ActionExecutedContext, which is very similar to ActionExecutingContext in the types of information you can get with these exceptions:
- There is no ActionParameters dictionary property.
- You will get some information related to an unhandled exception:
- Exception - the exception that was thrown by the action
- ExceptionHandled - set this to true if you've handled the exception in OnActionExecuted (otherwise it will be bubbled up)
- Canceled - this can get a bit confusing, but if the process was canceled by setting a different result in OnActionExecuting this will be set to 'true', or you can set this to 'true' yourself to cancel further processing. For more info, see this post on how MVC handles filters and this discussion on the Canceled property.
I did another "kitchen sink" view of an ActionExecutedContext object:
[MyCustomControllerAttribute1] | |
[MyCustomControllerAttribute2] | |
public class HomeController : Controller | |
{ | |
public ActionExecutedContext FilterExecutedContext; | |
public ActionResult Index(string id, string anotherParam) | |
{ | |
return View(); | |
} | |
[KitchenSinkActionExecutedFilter] | |
[MyCustomActionAttribute1] | |
[MyCustomActionAttribute2] | |
public ActionResult OnActionExecutedAction(string id, string anotherParam) | |
{ | |
if(anotherParam == "withException") | |
throw new SyntaxErrorException("I just wanted to throw an interesting exception!"); | |
return View(FilterExecutedContext); | |
} | |
} | |
public class KitchenSinkActionExecutedFilterAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
filterContext.ExceptionHandled = true; | |
filterContext.Result = new ViewResult(); | |
(filterContext.Result as ViewResult).ViewData.Model = filterContext; | |
} | |
} |
Paired with a slightly different View, which results in:
Note that one of the most interesting things you can do is to change the result of the action (like I did to make the Kitchen Sink example possible). For instance, if you wanted to redirect to another action, show a different view, etc,