Modify a model in an ActionFilter
I have an actionfilter that I am running OnActionExecuting in ASP.NET MVC 2. Essentially I would like the actionfilter to sanitize my data and replace the current model (which will be passed to subsequent action filters and also my action met开发者_如何学编程hod) with the sanitized model. Is this possible and is it a bad idea - if so why?
Thank you in advance, JP
If you need to deal with your models, you're likely going to be dealing more within the scope of a single Controller (unless all your Controllers use the same model types?). An alternate approach would be to override the OnActionExecuting()
and OnActionExecuted()
methods of the Controllers themselves. This allows you to keep your business logic within the controller scope.
Generally ActionFilters are used for cross-cutting concerns - something that you want to run for many action methods, regardless of where they exist in the app. So unless your model sanitization logic applies across many controllers and actions, or is very generic (which perhaps it is, in which case your approach is probably good), you might want to bring it out of the filters and into your controllers. If it's something that can apply broadly, then an ActionFilter is just fine.
Here's for MVC v1, I hope this is not changed in v2:
var view = filterContext.Result as ViewResultBase;
if (view != null)
view.ViewData.Model ...
I don't see why you want to do it in OnActionExecuting, but if you must, do it there, and set some flag (private field) that OnActionExecuted has to tweak the resulting Model. But you'll have to use the latter anyway, except if you assign the .Result - in this case your action won't be called at all and the assigned result will be used.
BTW, for MVC 3 & 4:
filterContext.Controller.ViewData.Model
精彩评论