将所有用户数据保存在 Forms 身份验证 cookie 中

Save All user data in Forms authentication cookies

我想存储电子邮件、column1 和 column2 以及用户类型。 它要求在每次页面加载时检查 column1 和 colmun2 值,我不想每次都从数据库中获取。

如何执行?

string type = User.Type;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, lg.UserName, DateTime.Now, DateTime.Now.AddMinutes(50), ckbRemember.Checked, User.Type,FormsAuthentication.FormsCookiePath);

您可以将最后一个参数设置为 comma-delimited 字符串,如下面的代码所示。

FormsAuthenticationTicket ticket = null;
ticket = new FormsAuthenticationTicket(1, lg.UserName, DateTime.Now, 
        DateTime.Now.AddMinutes(50), ckbRemember.Checked,
        email + "," + column1 + ","+ column2 + "," + type);
//or just use line of code below after creating ticket object
//ticket.UserData = email + "," + column1 + ","+ column2 + "," + type;

然后,当你想读取forms authentication ticket的用户数据时,可以使用下面的代码。

FormsIdentity identity = (FormsIdentity)Context.User.Identity;
userData = identity.Ticket.UserData;
string[] data =  userData.Split(",".ToCharArray());
//get the data stored in UserData property of forms authentication ticket
string email =  data[0];
string column1 =  data[1];
string column2 = data[2];
string  userType = data[3];