[英]Calling action filter automatically in MVC5
I'm trying to develop a plugin for nopcommerce and trying to catch model for a page (after submitted) in an action filter so that I can make some changes to model properties. 我正在尝试为nopcommerce开发插件,并试图在动作过滤器中捕获页面模型(提交后),以便对模型属性进行一些更改。
public ActionResult Index()
{
Data dt = new Data();
dt.id = 54;
dt.name = "something";
return View(dt);
}
and this is the fitler: 这是钳工:
public class ModelChangerAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Data dt = new Data();
dt = (Data) filterContext.Controller.ViewData.Model;
dt.id++;
dt.name += " someotherthing";
filterContext.HttpContext.Items["dt"] = dt;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//throw new NotImplementedException();
}
}
But for action filter to run I need to specify it before method in controller. 但是要运行动作过滤器,我需要在控制器中的方法之前指定它。 And I'm not down with that. 我并没有为此感到失望。
don't want to do this: 不想这样做:
[ModelChangerAttribute]
public ActionResult Index()
{
...
So is it possible to call filter automatically each time a controller method is run? 那么是否可以在每次运行控制器方法时自动调用filter?
Please provide an example HERE . 请在此处提供示例。
in App_Start/FilterConfig.cs: 在App_Start / FilterConfig.cs中:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ModelChangerAttribute());
}
}
Additional info: you should call this in global.asax in Application_Start(): 附加信息:您应该在Application_Start()的global.asax中调用它:
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.