尽量避免使用Session,如果您可以在不使用Seed的情况下离开,这将使多服务器部署变得更容易一些.很可能,姓名和邮箱很容易成为cookie的候选对象.伪造cookie很容易,因此根据您的安全需要,userid可能不是一个好主意.
表单验证cookie是加密的,您可以向这些cookie中添加额外的数据(请参阅下面的详细信息).它可能是可以破解的,但不像一个简单的cookies 那么容易.
下面是我在过go 使用的代码,这些代码经过了轻微修改,删除了一些特定于项目的细节.在登录控件的LoggedIn事件中调用此函数.
void AddUserIDToAuthCookie(string userID)
{
//There is no way to directly set the userdata portion of a FormAuthenticationTicket
//without re-writing the login portion of the Login control
//
//I find it easier to pull the cookie that the Login control inserted out
//and create a new cookie with the userdata set
HttpCookie authCookie = Response.Cookies[AUTH_COOKIE];
if(authCookie == null)
{
return;
}
Response.Cookies.Remove(AUTH_COOKIE);
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
var newTicket =
new FormsAuthenticationTicket(oldTicket.Version, oldTicket.Name, oldTicket.IssueDate, oldTicket.Expiration,
oldTicket.IsPersistent, userID, oldTicket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(authCookie);
}
仅供参考,我从一个旧项目中复制了它,并在这里编辑它,以删除一些特定于项目的位,因此它可能无法编译,但会非常接近.
若要在您的网页中获取ID.
FormsAuthenticationTicket ticket = ((FormsIdentity) Page.User.Identity).Ticket;
string id = ticket.UserData;
我使用这种机制来存储一个不属于aspnetdb用户数据的id.如果您的所有身份数据都由aspnetdb处理,则您可能只需要访问该页面.使用者标识对象.