【问题标题】:Calling action filter automatically in MVC5在 MVC5 中自动调用动作过滤器
【发布时间】:2015-11-26 08:22:01
【问题描述】:

我正在尝试为 nopcommerce 开发一个插件,并尝试在操作过滤器中捕获页面的模型(提交后),以便我可以对模型属性进行一些更改。

    public ActionResult Index()
    {
        Data dt = new Data();

        dt.id = 54;
        dt.name = "something";
        return View(dt);
    }

这是装配工:

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();
        }
    }

但是要运行动作过滤器,我需要在控制器中的方法之前指定它。我对此并不失望。

不想这样做:

        [ModelChangerAttribute]
        public ActionResult Index()
        {
            ...

那么是否可以在每次运行控制器方法时自动调用过滤器?

请在此处提供一个示例。

【问题讨论】:

  • 你可以将它应用到控制器上,如果你想要它用于其中的所有方法。
  • @StephenMuecke 我根本不想编辑控制器。
  • 不确定编辑控制器是什么意思?它的[ModelChangerAttribute] public class yourController : Controller { 或将其全局注册到global.asax 中的所有控制器
  • 如何在全球范围内注册?一个例子将不胜感激。

标签: c# asp.net-mvc-5 action-filter


【解决方案1】:

在 App_Start/FilterConfig.cs 中:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ModelChangerAttribute());
    }
}

附加信息:您应该在 Application_Start() 的 global.asax 中调用它:

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

【讨论】:

  • 这适用于每个控制器?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多