2009-11-30 65 views
7

Tôi đang gặp sự cố khi tạo cookie không liên tục bằng cách sử dụng Biểu mẫu xác thựcTicket. Tôi muốn lưu trữ userdata trong vé, vì vậy tôi không thể sử dụng các phương thức FormsAuthentication.SetAuthCookie() hoặc FormsAuthentication.GetAuthCookie(). Bởi vì điều này tôi cần phải tạo FormsAuthenticationTicket và lưu nó trong một HttpCookie.Tạo cookie không liên tục bằng FormsAuthenticationTicket

Mã của tôi trông như thế này:

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); 

Khi isPersistent biến là đúng tất cả mọi thứ hoạt động tốt và cookie vẫn kiên trì. Nhưng khi isPersistent là sai thì cookie dường như vẫn tồn tại. Tôi đăng nhập trong cửa sổ trình duyệt, đóng cửa sổ và mở lại trình duyệt và tôi vẫn đăng nhập. Làm thế nào để tôi đặt cookie thành không liên tục?

Cookie không liên tục giống như cookie phiên không? Thông tin cookie được lưu trữ trong sessiondata trên máy chủ hay là cookie được chuyển trong mọi yêu cầu/phản hồi tới máy chủ?

Trả lời

3

thử xóa:

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

... và thay thế nó bằng:

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

Các vấn đề liên quan