2010-06-29 36 views
61

tôi đang tạo ra các tập tin cookie với dòng sau:Làm thế nào để tạo cookie liên tục trong asp.net?

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); 
userid.Expires.AddYears(1); 
Response.Cookies.Add(userid); 

Now Làm thế nào để làm cho nó dai dẳng?

Vì nếu tôi truy cập lại cùng một trang sau khi đóng trình duyệt, tôi không thể lấy lại được.

Trả lời

85

Đây là cách bạn có thể làm điều đó.

Viết cookie liên tục.

//create a cookie 
HttpCookie myCookie = new HttpCookie("myCookie"); 

//Add key-values in the cookie 
myCookie.Values.Add("userid", objUser.id.ToString()); 

//set cookie expiry date-time. Made it to last for next 12 hours. 
myCookie.Expires = DateTime.Now.AddHours(12); 

//Most important, write the cookie to client. 
Response.Cookies.Add(myCookie); 

Đọc cookie liên tục.

//Assuming user comes back after several hours. several < 12. 
//Read the cookie from Request. 
HttpCookie myCookie = Request.Cookies["myCookie"]; 
if (myCookie == null) 
{ 
    //No cookie found or cookie expired. 
    //Handle the situation here, Redirect the user or simply return; 
} 

//ok - cookie is found. 
//Gracefully check if the cookie has the key-value as expected. 
if (!string.IsNullOrEmpty(myCookie.Values["userid"])) 
{ 
    string userId = myCookie.Values["userid"].ToString(); 
    //Yes userId is found. Mission accomplished. 
} 
+3

Đọc mã cookie liên tục không hoạt động đối với tôi. Xem câu trả lời của tôi trong bài đăng này. –

+3

Mã của bạn không có chức năng khác với mã được đăng trong câu hỏi gốc mặc dù cookie của bạn hết hạn sau 12 giờ và OP sẽ hoạt động trong một năm. – Ortund

+2

Cookie này không liên tục, nếu khách hàng đóng trình duyệt mà cookie sẽ biến mất. Câu hỏi đặt ra là cách viết cookie liên tục, thay vì cookie 'phiên'. – Felype

0

Bạn cần phải thêm này như dòng cuối cùng ...

HttpContext.Current.Response.Cookies.Add(userid); 

Khi bạn cần phải đọc giá trị của cookie, bạn muốn sử dụng một phương pháp tương tự như sau:

string cookieUserID= String.Empty; 

    try 
    { 
     if (HttpContext.Current.Request.Cookies["userid"] != null) 
     { 
      cookieUserID = HttpContext.Current.Request.Cookies["userid"]; 
     } 
    } 
    catch (Exception ex) 
    { 
     //handle error 
    } 

    return cookieUserID; 
22

FWIW rất cẩn thận khi lưu trữ thứ gì đó như userid trong cookie không được mã hóa. Làm điều này làm cho trang web của bạn dễ bị ngộ độc cookie, nơi người dùng có thể dễ dàng mạo danh người dùng khác. Nếu bạn đang xem xét một cái gì đó như thế này tôi rất muốn khuyên bạn nên sử dụng cookie xác thực biểu mẫu trực tiếp.

bool persist = true; 

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist); 

cookie.Expires = DateTime.Now.AddMonths(3); 

var ticket = FormsAuthentication.Decrypt(cookie.Value); 

var userData = "store any string values you want inside the ticket 
       extra than user id that will be encrypted" 

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, 
    ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData); 

cookie.Value = FormsAuthentication.Encrypt(newTicket); 

Response.Cookies.Add(cookie); 

Sau đó, bạn có thể đọc bất cứ lúc nào từ một trang ASP.NET bằng cách làm

string userId = null; 
if (this.Context.User.Identity.IsAuthenticated) 
{ 
    userId = this.Context.User.Identity.Name; 
} 
+1

Anh ta có nói cookie FormsAuthentication không? Và tại sao sử dụng 'var' khi bạn biết loại. –

+0

Cảm ơn bạn đã quan tâm đến bảo mật nhưng tôi đang sử dụng mã hóa cho các cookie! – Vikas

+14

Do đặc tả dự phòng của các biến là thừa. Và vì câu hỏi đặc biệt cho thấy userid là giá trị để lưu trữ trong cookie, Cookie FormsAuth là giải pháp chính xác nhất cho IMO này. –

0

// thêm cookie

var panelIdCookie = new HttpCookie("panelIdCookie"); 
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture)); 
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie); 

// đọc cookie

var httpCookie = Request.Cookies["panelIdCookie"]; 
       if (httpCookie != null) 
       { 
        panelId = Convert.ToInt32(httpCookie["panelId"]); 
       } 
32

Mặc dù câu trả lời được chấp nhận là chính xác, nó d oes không nêu lý do tại sao mã ban đầu không hoạt động.

đang xấu từ câu hỏi của bạn:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); 
userid.Expires.AddYears(1); 
Response.Cookies.Add(userid); 

Hãy nhìn vào dòng thứ hai. Cơ sở cho hết hạn là thuộc tính Expires có chứa mặc định là 1/1/0001. Mã trên được đánh giá là 1/1/0002. Hơn nữa việc đánh giá không được lưu lại cho tài sản. Thay vào đó, thuộc tính Expires sẽ được thiết lập dựa trên ngày hiện tại.

đang Corrected:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); 
userid.Expires = DateTime.Now.AddYears(1); 
Response.Cookies.Add(userid); 
1

Như tôi hiểu bạn sử dụng xác thực ASP.NET và để thiết lập cookie bạn cần phải thiết lập FormsAuthenticationTicket.IsPersistent = true Đó là ý tưởng chính.

bool isPersisted = true; 
var authTicket = new FormsAuthenticationTicket(
1, 
user_name, 
DateTime.Now, 
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year) 
isPersisted,//THIS IS THE MAIN FLAG 
addition_data); 
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket); 
    if (isPersisted) 
     authCookie.Expires = authTicket.Expiration; 

HttpContext.Current.Response.Cookies.Add(authCookie); 
Các vấn đề liên quan