我在使用FormsAuthenticationTicket创建非持久性cookie时遇到问题。我想将用户数据存储在票证中,因此无法使用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是否与 session cookie相同? cookie信息存储在服务器上的sessiondata中,还是cookie在每次请求/响应中都传输到服务器?

最佳答案

尝试删除:
if (isPersistent) { cookie.Expires = expiration; }
...并替换为:
if (!isPersistent) { cookie.Expires = DateTime.Now.AddYears(-1); }

07-24 14:10