Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 Custom OnActionExecuting Global.asx Filter is not being Triggered

I am trying to create a Global filter that will run for every action I have if the user is logged in. From what I have read there are two steps necessary. First, add the new filter within the Global.asx file.

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

Then I have to create the filter itself in the filters folder.

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

How can I make this work? Is there a better way? I can add this to all the controllers and it works, that's just less than ideal.

like image 637
Jed Grant Avatar asked Feb 18 '23 17:02

Jed Grant


1 Answers

I had the same experience. you can build a BaseController class and put the filter definition in it. Then all of your controllers must be inherited from BaseController class. So you don't have to use filter class in all controllers.

something like this:

    public class BaseController : Controller
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
         ...
         }
    }

In controllers:

public class SampleController : BaseController
{
 ...
}
like image 180
Bahman Avatar answered Feb 22 '23 00:02

Bahman