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.

// Assigns a cookie, receives a name and a value. It is configured to last for 15 minutes.
function setCookie(name, value) {  
    var expiry = new Date();
    expiry.setMinutes(expiry.getMinutes() + 15);
    document.cookie = name + "=" + (value) + "; path=/; expires=" + expiry.toGMTString();
}

// Gets a cookie's value. If it's not set it returns null.
function getCookie(name) {  
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? (value[1]) : null;
}

// "Deletes" a cookie. 
function deleteCookie(name) {  
    document.cookie = name + '=; path=/; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}

Another and possibly easier way is to use a jQuery plugin that has been heavily tested.

Using this plug in, the above example will translate to something like this:

// Creates a cookie
Cookies.set('cookiename', 'value');

// This cookie will expire in 1 day
Cookies.set('cookiename', 'value', { expires: 1 });

// Read a cookie
Cookies.get('cookiename');

// Deletes a cookie
Cookies.remove('cookiename');  

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);  
// Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];  
if (myCookie == null)  
{
    // No cookie found or cookie expired. :(
}

// Verify the cookie value
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))  
{
    // userId is found.
    string userId = myCookie.Values["userid"].ToString();    
}

if (Request.Cookies["userId"] != null)  
{
    // This will delete the cookie userId
    Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-1);  
}

If you wish to access your cookie only by the web server, be sure to use the HttpOnly property!

Bibliography

"ASP.NET Cookies Overview." ASP.NET Cookies Overview. Microsoft, n.d. Web. 13 July 2015. https://msdn.microsoft.com/en-us/library/ms178194(v=vs.140).aspx.

"HTTP Cookies." Mozilla Developer Network. Mozilla, n.d. Web. 13 July 2015. https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies.

Author image
Profound Jack Daniel's enthusiast. In my free time, I like to code and lift weights. Proud owner of two Siberian huskies. Professional Services Manager at Medallia.