我正在尝试创建一个全局过滤器,如果用户登录,它将针对我拥有的每个操作运行。从我所阅读的内容来看,有两个步骤是必要的。首先,在 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();
}
}
然后我必须在过滤器文件夹中创建过滤器本身。
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);
}
}
我怎样才能使这项工作?有没有更好的办法?我可以将它添加到所有控制器中并且它可以工作,但这并不理想。