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 to make it persistent?
Because if I visit the same page again after closing the browser, I'm unable to get it back.
FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.
Then you can read this at any time from an ASP.NET page by doing
As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.
Although the accepted answer is correct, it does not state why the original code failed to work.
Bad code from your question:
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:
You need to add this as the last line...
When you need to read the value of the cookie, you'd use a method similar to this:
Here's how you can do that.
Writing the persistent cookie.
Reading the persistent cookie.
//add cookie
//read cookie