Web Development

How To Make Cookies In 5 Minutes?

Tri Nguyen | July 22, 2011 | ADD COMMENT

What is cookie?

Cookie, also known as HTTP Cookie, Web Cookie, and Browser Cookie, is often used to send state information to the browsers and for browsers to return state of information back to server. Cookie is not a software and cannot be programmed. It's simply a plain text file that stores user activity, preferences, session data, and more.

Creating Cookie

Creating a cookie means create a text file with specific data on the user machine. A good example would be the the "Like" feature below. When user click on the "Like" button, it inserts a vote for this blog entry as well as creating a cookie on the user machine that will expired in 24 hours. On Page Load, if the cookie exist, it hides the vote option and/or denied multiple vote within 24 hours, if user somehow again access to the vote function.


This cookie basically does nothing except storing the date and time of user last visit.

//Create new Http Cookie
HttpCookie my_cookie = new HttpCookie("cookie_name");

my_cookie["last_visit"] = DateTime.Now.ToLongDateString();

my_cookie.Expires = DateTime.Now.AddDays(30); //expired in 30 days

Response.Cookies.Add(my_cookie); //Add cookie to user machine

Deleting Cookie

The only way to remove a cookie is to delete manually, assuming you know where your browser stores cookies, or replacing with an expired cookie. There are couple ways to carry out this task in ASP.NET:

Example - Delete By Replacing With An Expired Cookie
//Request cookie from user machine
HttpCookie my_cookie = Request.Cookies["cookie_name"];

//If cookie exist on user machine, then replace with an expired cookie
if (my_cookie)
    //Create a new cookie with the same name
    my_cookie = new HttpCookie("cookie_name");

    //Set expiration to the past hour to make it expired
    my_cookie.Expires = DateTime.Now.AddHours(-1);

    //Add to user machine, which will replace the existing one since they have the same name
C# Example - Delete By Calling ASP.NET Built-in Function

This is a single line function call but the code behind really does the same as above.