session state - How do store a value throughout an asp.net mvc (razor 3) application? -


for example if user loggged in, best approach storing userid and/or his/her roles/groups? obvious approaches cookies , session? other options?

at least, using forms authentication can put user id , roles in formst auth ticket.

here'a example of how did it:

    public static httpcookie createcookie(iuseridvalue userid, string name, ienumerable<int> group, bool ispersistent = false)     {         var user = new authenticationticketdata() { groups = @group, userid = userid };         var ft = new formsauthenticationticket(2, name, datetime.now, datetime.now.add(formsauthentication.timeout),                                                ispersistent, user.pack());         var ck = new httpcookie(formsauthentication.formscookiename)                      {                          value = formsauthentication.encrypt(ft),                          path = formsauthentication.formscookiepath,                          domain = formsauthentication.cookiedomain                      };         if (ispersistent)         {             ck.expires = datetime.now.add(formsauthentication.timeout);         }         return ck;     }    public static string pack(this authenticationticketdata data)     {         if (data == null) throw new argumentnullexception("data");         return string.format("{0};{1}",packuserid(data.userid),string.join(",",data.groups));     }      static string packuserid(iuseridvalue uid)     {         if (uid == null) throw new argumentnullexception("uid");         var tpn = uid.gettype().getfulltypename();         return string.format("{0}|{1}",tpn,uid.tostring());     }   public static httpcookie setauthcookie(this httpresponse response,iuseridvalue userid, string name, ienumerable<int> group, bool ispersistent = false)     {         var ck = createcookie(userid, name, group, ispersistent);         response.appendcookie(ck);         return ck;     } 

another alternative keep user session (no relation session) in database, table(guid,username,userid,roles,expireat). approach more suitable if want keep track of when user logins/logout or if you're using own authentication (not forms auth).


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -