c# - ASP.NET MVC : Register action filter without modifying controller

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

我正在使用 nopCommerce,我需要添加我唯一的 Action Filter,但是,我不想修改核心 Controller 以避免我的代码在发布新更新时被覆盖。

我已经设置了我的 Action 过滤器:

public class ProductActionFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            ...
        }
        base.OnActionExecuted(filterContext);
    }

}

如果我要修改 Controller ,我可以将 [ProductActionFilter] 添加到我希望它分配给的操作中。

有没有一种方法可以在不修改 Controller 的情况下将我的自定义 Action 过滤器注册到特定 Action ?

最佳答案

我认为全局过滤器正是您所需要的。

创建过滤器后,将其注册到 global.asax 中:

protected void Application_Start() {

    AreaRegistration.RegisterAllAreas();

    // Register global filter
    GlobalFilters.Filters.Add(new MyActionFilterAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes); 
}

如果您不想将其应用于所有操作,请添加自定义验证逻辑以进行过滤。

关于c# - ASP.NET MVC : Register action filter without modifying controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8786192/

相关文章:

javascript - 带有 jquery ui 选项卡的 MVC 4

c# - 在 controller.OnActionExecuting 中设置结果后 ActionFilter 未触发

c# - 正则表达式从名称中提取首字母

c# - Entity Framework ,防止重复记录,同时连接

c# - 在 Code.cs 和 Code.cs[design] 中正确地从 Windows 窗体中删除一个项目

c# - 是否可以使用属性在属性更改时自动引发事件

asp.net-mvc - 如何使用 ViewBag 显示列表

c# - 在 ASP.NET Core 中重命名 AccountController

c# - 多个ActionFilterAttribute的执行顺序有保证吗?

c# - 为什么在 WebAPI 自定义操作过滤器中获取 Request.UserHostAddress 时总是获取相同的 IP?