Search Result

Working with cookies in JavaScript and ASP.NET

Cookies are small pieces of data that are sent from the website and then are stored in the user's web brower while the user is browsing a determined website.

In the early days of the Internet, cookies were designed as a method to identify if a particular request came from the same web browser or not, useful for keeping a user logged in, for example.

Nowadays, cookies are used to store information (usually short text strings) in a client's computer for a particular website. This allows an application to store different settings, not only a user's login information.

For example, Amazon uses cookies to store items in your shopping cart, along with many other things. Since cookies can have an expiration time, the information stored within them is persistant in a determined timespan (this is how you can keep login information, among other things).

How to use cookies?

There are many ways, since cookies can be accesed by a web server or the client's computer.

Using JavaScript

This code snippet allows you to create, read and "delete" a cookie using just JavaScript. Cookies aren't really deleted, they just expire.

Using ASP.NET

Session cookies are deleted when the user closes the browser. Persitant cookies are stored in your computer's hard drive and will last for a specified timespan.

C# example

// Creates a cookie with a name.
HttpCookie myCookie = new HttpCookie("myCookie");
// Add key-values in the cookie.
myCookie.Values.Add("userid", MyUser.Id.ToString());
// Set a cookie expiry by a DateTime, this cookie will last for 24 hours. By assigning a date of expiration, this becomes a persistant cookie.
myCookie.Expires = DateTime.Now.AddHours(24);
// Write the cookie to client's browser, this is an important step.
Response.Cookies.Add(myCookie);