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.
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
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With