繁体   English   中英

在asp.net mvc中设置当前用户

[英]set current user in asp.net mvc

我不确定这是否是最好的方法,但我希望在当前用户的所有请求期间保持用户对象的活动状态。 通过阅读几个资源,我了解到你应该创建自己的IPrinciple来保存它。 但我不希望每个身份验证请求都触发数据库。 关于如何处理这个问题的任何建议? 缓存db请求是个好主意吗?

 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            User user;
            using (HgDataContext hg = new HgDataContext())
            {
                if (Session["user"] != null)
                {
                   user = (from u in hg.Users where u.EmailAddress == authTicket.Name select u).Single();
                } else
                {
                   user = Session["user"] as User;
                } 
            }
            var principal = new HgPrincipal(user);
            Context.User = principal;
        }
    }

会话可能是执行此操作的适当方式,实际上是我提倡的Session的少数用法之一。

我现在使用以下代码来缓存用户,请注意在更新后删除缓存!

 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                User user;
                Cache cache = HttpContext.Current.Cache;
                using (HgDataContext hg = new HgDataContext())
                {
                    user =  cache[authTicket.Name] as User;
                    if (user == null)
                    {
                       user = (from u in hg.Users where u.EmailAddress == authTicket.Name select u).Single();
                       cache[authTicket.Name] = user;
                    }
                }
                var principal = new HgPrincipal(user);
                Context.User = principal;
            }
        }

创建自己的IPrincipal实现是最好的方法。 只要在更新时刷新数据,为用户缓存数据就不是问题。 通常只有用户自己才有能力改变他的个人数据,因此不难做到。 您可以在此博文中看到更改当前用户的简便方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM