I am creating cookies with following lines:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires.AddYears(1); Response.Cookies.Add(userid);
Now how can I make it persistent?
If I visit the same page again after closing the browser, I'm unable to get it back.
Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text file in the hard disk of the computer. Non-Persistent Cookies: Non-Persistent cookies are temporary. They are also called in-memory cookies and session-based cookies.
Persistent cookies are stored on a user's device to hold usage information, settings, personalizations, or sign-on credentials. The primary purpose of persistent cookies is to provide users with an immersive and seamless browsing experience by auto-filling information that the user may have already provided.
If a cookie is valid and can be read by the domain, it will be passed along with the HTTP request to the domain that it originated from. If you want a cookie to expire at a specific time, you need to set an expiration date.
Here's how you can do that.
Writing the persistent cookie.
//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);
Reading the persistent cookie.
//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. }
Although the accepted answer is correct, it does not state why the original code failed to work.
Bad code from your question:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires.AddYears(1); Response.Cookies.Add(userid);
Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.
Corrected code:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(userid);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With