加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – MVC4自定义OnActionExecuting Global.asx过滤

发布时间:2020-12-16 07:19:01 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试创建一个全局过滤器,该过滤器将针对用户登录时的每个操作运行.从我所看到的,有两个必要的步骤.首先,在Global.asx文件中添加新过滤器. public class MvcApplication : System.Web.HttpApplication{ //I added this public static void RegisterGlob
我正在尝试创建一个全局过滤器,该过滤器将针对用户登录时的每个操作运行.从我所看到的,有两个必要的步骤.首先,在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();
    }
}

然后我必须在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);
    }
}

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

解决方法

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

这样的事情:

public class BaseController : Controller
    {

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

在控制器中:

public class SampleController : BaseController
{
 ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读