Install current user in asp.net mvc

I'm not sure if this is the best way to do this, but I want to keep the user live object during all requests of the current user. From reading several resources, I found out that you must create your own IPrinciple that contains this. But I do not want to run the database every authentication request. Any recommendations on how to handle this? Is caching a 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; } } 
+6
c # asp.net-mvc
source share
3 answers

Now I am using the following code that caches the user, make sure you delete the cache after the update!

  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; } } 
+2
source share

A session is probably the right way to do this, and in fact it is one of the few uses of Session that I would advocate.

+3
source share

Creating your own IPrincipal implementation is the best way to do this. This is not a data caching problem for the user if you update it, if it is updated. Usually only the user himself has the ability to change his personal data, so it’s easy to do so. You can see an easy way to change the current user in this blog post .

0
source share

All Articles