How to assign cookie expiry date?

4.1k views Asked by At

I am trying to learn about cookies. But there is a point I can't understand. Hope, you can help me.

I wrote a short code:

using System;
using System.Web;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["Test2"] == null)
            {
                Response.Cookies["Test2"]["Address"] = "Home";
                Response.Cookies["Test2"].Expires = DateTime.Now.AddSeconds(60);
            }

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Cookies["Test2"]["Address"] = "Work";
        }
    }
}

Firstly, I want to check if there is a cookie with the name "Test2". It creates a cookie with the name "Test2". Its expiry date is one minute later it has been created.

enter image description here

Then, I am clicking the button, it passes the if clause and change Address to Work. But when I look at the cookie expiry date is gone.

Expires: When the browsing session ends

http://i.imgur.com/uNWPBRF.png

Why does this expiry date change? Could you please help me?

1

There are 1 answers

0
Habib On BEST ANSWER

You are trying to modify the cookie , that will create a new cookie, and since you haven't specified the ExpiryDate it will be limited to when the session will end.

ASP.NET Cookies Overview

You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

Also:

If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded.

So your options are either not to modify the cookie value (use some other mechanism like DB), or specify a different expiry date with each modification.