使用FormsAuthenticationTicket创建非持久性cookie

时间:2009-11-30 11:53:16

标签: cookies forms-authentication httpcookie

我在使用FormsAuthenticationTicket创建非持久性cookie时遇到问题。我想在票证中存储userdata,因此我无法使用FormsAuthentication.SetAuthCookie()或FormsAuthentication.GetAuthCookie()方法。因此,我需要创建FormsAuthenticationTicket并将其存储在HttpCookie中。

我的代码如下所示:

DateTime expiration = DateTime.Now.AddDays(7);

// Create ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
    user.Email,
    DateTime.Now,
    expiration,
    isPersistent,
    userData,
    FormsAuthentication.FormsCookiePath);

// Create cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Path = FormsAuthentication.FormsCookiePath;
if (isPersistent)
    cookie.Expires = expiration;

// Add cookie to response
HttpContext.Current.Response.Cookies.Add(cookie);

当变量isPersistent为true时,一切正常并且cookie被保留。但是当isPersistent为false时,cookie似乎仍然存在。我在浏览器窗口中登录,关闭它并再次打开浏览器,我仍然登录。如何将cookie设置为非持久性?

非持久性cookie与会话cookie相同吗? cookie信息是存储在服务器上的sessiondata中还是在每次请求/响应服务器中传输cookie?

1 个答案:

答案 0 :(得分:3)

尝试删除:

if (isPersistent) { cookie.Expires = expiration; }

...并将其替换为:

if (!isPersistent) { cookie.Expires = DateTime.Now.AddYears(-1); }