How can I create persistent cookies in ASP.NET?

I am creating cookies with following lines:

HttpCookie userid = new HttpCookie("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.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

//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.

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.

Method 2

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",;

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",;
userid.Expires = DateTime.Now.AddYears(1);

Method 3

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.

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


Then you can read this at any time from an ASP.NET page by doing

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
    userId = this.Context.User.Identity.Name;

Method 4

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.

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


Method 5

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:

    string cookieUserID= String.Empty;

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

    return cookieUserID;

Method 6

//add cookie

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

//read cookie

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x