MVC4自定义OnActionExecuting Global.asx过滤器未被触发

Jed*_*ant 4 asp.net-mvc-4

我正在尝试创建一个全局过滤器,该过滤器将针对用户登录时的每个操作运行.从我所看到的,有两个必要的步骤.首先,在Global.asx文件中添加新过滤器.

public class MvcApplication : System.Web.HttpApplication
{
    //I added this
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new NotificationFilter());
    }
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我必须在filters文件夹中创建过滤器.

public class NotificationFilter : ActionFilterAttribute 
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    { //Breakpoint here is never triggered
        //This code doesn't work, but it's what I want to do
        if (WebSecurity.CurrentUserId > 0)
        {
            var notificationCount = db.Notifications.GroupBy(i => i.UserID).Count();
            if (notificationCount > 99)
            {
                ViewBag.Notifications = "99+";
            }
            else
            {
                ViewBag.Notifications = notificationCount;
            }
        }
        base.OnActionExecuting(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?有没有更好的办法?我可以将它添加到所有控制器并且它可以工作,这不太理想.

Bah*_*man 5

我有同样的经历.您可以构建一个BaseController类并将过滤器定义放入其中.然后,所有控制器必须从BaseController类继承.因此,您不必在所有控制器中使用过滤器类.

这样的事情:

    public class BaseController : Controller
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
         ...
         }
    }
Run Code Online (Sandbox Code Playgroud)

在控制器中:

public class SampleController : BaseController
{
 ...
}
Run Code Online (Sandbox Code Playgroud)