set current user in asp.net mvc

Posted by Tomh on Stack Overflow See other posts from Stack Overflow or by Tomh
Published on 2010-04-14T22:56:22Z Indexed on 2010/04/14 23:03 UTC
Read the original article Hit count: 340

Filed under:
|
|

Hey guys,

I'm not sure if this is the best way to do it, but I want to keep a user object alive during all requests of the current user. From reading several resources I learned that you should create your own IPrinciple which holds this. But I don't want to trigger the database every authentication request. Any recommendations on how to handle this? Is caching the db request a good idea?

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET