User Tools

Site Tools


notes:asp.net:cookies

Cookies in ASP.NET

Create a cookie:

// Check if the browser accepts cookies.
if (Request.Browser.Cookies)
{
    // If the cookie does not exist...
    if (Request.Cookies["LastVisit"] == null)
    {
        // Create the cookie. DateTime.MaxValue means that the cookie never expires.
        HttpCookie cookieLastVisit = new HttpCookie("LastVisit", DateTime.Now.ToString());
        // Set the expiration to tommorrow.
        cookieLastVisit.Expires = DateTime.Now.AddDays(1);
        // Add the cookie to the cookies collection.
        Response.Cookies.Add(cookieLastVisit);
     }
}

Update a cookie:

// Check if the browser accepts cookies.
if (Request.Browser.Cookies)
{
    // Get the cookie.
    HttpCookie cookieLastVisit = Request.Cookies["LastVisit"];
 
    // If the cookie exists...
    if (cookieLastVisit != null)
    {
        // Update value of the cookie.
        Response.Cookies["LastVisit"].Value = DateTime.Now.ToString();
        Response.Cookies["LastVisit"].Expires = DateTime.Now.AddDays(1);
    }
}

Remove a cookie:

// Set cookie to expire immediately.
Response.Cookies["LastVisit"].Expires = DateTime.Now;

Create a cookie and provide additional information:

// Create a cookie.
HttpCookie cookieUserInfo = new HttpCookie("UserInfo");
// Fill in the keys from the form data.
cookieUserInfo["Name"] = txtName.Text;
cookieUserInfo["Address"] = txtAddress.Text;
// Set the expiration.
cookieUserInfo.Expires = DateTime.Now.AddDays(30);
// Add the cookie to the cookies collection.
Response.Cookies.Add(cookieUserInfo);

Read information from a cookie:

// Get the cookie.
HttpCookie cookieUserInfo = Request.Cookies["UserInfo"];
// Fill in the fields from the cookie's keys.
txtName.Text = cookieUserInfo["Name"];
txtAddress.Text = cookieUserInfo["Address"];
notes/asp.net/cookies.txt · Last modified: 2016/03/29 by admin