c# - MVC5 中自动调用 Action 过滤器

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

我正在尝试为 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();
        }
    }

但是为了运行操作过滤器,我需要在 Controller 中的方法之前指定它。我对此并不满意。

不想这样做:

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

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

请在此处提供示例。

最佳答案

在 App_Start/FilterConfig.cs 中:

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

其他信息:您应该在 Global.asax 的 Application_Start() 中调用它:

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

关于c# - MVC5 中自动调用 Action 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33933636/

相关文章:

c# - CSS:使用宽度百分比定位子表?

c# - MVC View 中需要维护的许多字段

asp.net-mvc-5 - OnValidateIdentity 禁用 MVC OWIN 记住我选项

.net - ASP.NET MVC、ActionFilters、静态类和传递数据

c# - 在 ServiceStack 请求过滤器上传递/公开 T

asp.net-mvc - 不允许子操作执行重定向操作 - MVC

c# - AND C# 中的两个位图

c# - 抛出异常而不是处理返回

c# - 在特定日期触发电子邮件

c# - 上传后和将其保存到数据库之前调整图像大小