Altering the ASP NET MVC model with an ActionFilter
Full source code here.
Action filters are executed before and/or after the execution of an action method, they can be used to modify how an action executes or to perform a separate task, such as authorization or logging.
Action filters can be applied globally, at the controller level, or on an action method.
See here for more details.
In this post I’ll deal with how action filters allow you intercept an outgoing response to change a value in the returned model.
Action filter
Create a filter that inherits from ActionFilterAttribute
and override the OnActionExecuted
method.
public override void OnActionExecuted(ActionExecutedContext filterContext)
From the filterContext we can get model.
var model = filterContext.Controller.ViewData.Model as BaseModel;
Any value in the BaseModel
can now be changed, in the example provided I change the MeetingDate
property.
This action filter to needs to be applied to the appropriate action methods. I’m going to register the filter globally, in this way it will run on all executed action methods.
Go to the FilterConfig
class to register the filter.
1public static void RegisterGlobalFilters(GlobalFilterCollection filters)
2{
3 filters.Add(new HandleErrorAttribute());
4 filters.Add(new ModelAlterFilterAttribute());
5}
That is all you need to do to create an action filter, register it and to alter the returned model.
As an aside, if you want to alter the value of an incoming parameter you override the OnActionExecuting
method of the action filter.
In this example customerID
is just an int
but this approach will work for complex models too.
1public override void OnActionExecuting(ActionExecutingContext filterContext)
2{
3 var actionParams = filterContext.ActionParameters;
4
5 object customerID;
6 actionParams.TryGetValue("customerid", out customerID);
7 if (customerID != null)
8 {
9 customerID = 222;
10 }
11
12 base.OnActionExecuting(filterContext);
13}
In the next post I show how you to selectively disable a global action filter on specific action methods or controllers.
Full source code here.