Geekpedia Programming Tutorials






Handling cookies in ASP .NET

How to create a cookie, how to get the value stored in a cookie, set the lifetime, path and domain for a cookie, edit a cookie, delete a cookie, remove subkeys from a cookie...

On Tuesday, August 3rd 2004 at 02:12 AM
By Andrei Pociu (View Profile)
*****   (Rated 4.4 with 116 votes)
Contextual Ads
More ASP.NET Resources
Advertisement
Here's a tutorial that shows you how to use cookies in ASP .NET. I'm not going to explain the role of cookies in web applications or cover any other theoretical aspect of cookies. There are many (similar) ways to handle cookies in ASP .NET. I'm only going to show you one of the ways, my way. Oh, and we're going to use C#, although the code can be adapted to Visual Basic .NET easily.



How to create a cookie.

Here's a new cookie named cakes.





HttpCookie myCookie = new HttpCookie("cakes");



We created the cookie but there are no keys with values in it, so for now it's useless. So let's add some:





myCookie.Values.Add("muffin", "chocolate");

myCookie.Values.Add("babka", "cinnamon");



We also need to add the cookie to the cookie collection (consider it a cookie jar ):





Response.Cookies.Add(myCookie);



How to get the value stored in a cookie.

Here's how to get the keys and values stored in a cookie:





Response.Write(myCookie.Value.ToString());



The output to using this with the previous created cookie is this: "muffin=chocolate&babka=cinnamon".



However, most of the time you'll want to get the value stored at a specific key. If we want to find the value stored at our babka key, we use this:





Response.Write(myCookie["babka"].ToString());



Set the lifetime for a cookie.

You can easily set the time when a cookie expires. We'll set the Expires property of myCookie to the current time + 12 hours:





myCookie.Expires = DateTime.Now.AddHours(12);



This cookie will expire in twelve hours starting now. You could as well make it expire after a week:





myCookie.Expires = DateTime.Now.AddDays(7);



Also note that if you don't set a cookie's expiration date & time a transient cookie will be created - a cookie which only exists in the current browser instance. So if you want the cookie to be stored as a file you need to set this property.


Setting the cookie's path.

Sometimes you'll want to set a path for a cookie so that it will be available only for that path in your website (ex.: www.geekpedia.com/forums). You can set a cookie's path with the Path property:





myCookie.Path = "/forums";



Setting the domain for a cookie.

Perhaps instead of using http://www.geekpedia.com/forums path style to your forums, you would use a subdomain like http://forums.geekpedia.com. The Domain property should do it:





myCookie.Domain = "forums.geekpedia.com";



How to edit a cookie.

You don't actually edit a cookie, you simply overwrite it by creating a new cookie with the same key(s).



How to destroy / delete a cookie.

There's no method called Delete which deletes the cookie you want. What you can do if you have to get rid of a cookie is to set its expiration date to a date that has already passed, for example a day earlier. This way the browser will destroy it.





myCookie.Expires = DateTime.Now.AddDays(-1);



How to remove a subkey from a cookie.

This is one of the problems I encountered with cookies. Fortunately I found an answer on MSDN. You can use the Remove method:





myCookie.Values.Remove("babka");



However, you don't usually remove a subkey immediatly after creating it, so first we need to retrieve the cookie, remove the subkey and then add it back to the Cookies collection:





// Get the cookie from the collection (jar)

myCookie = Request.Cookies["cakes"];

// Remove the key 'babka'

myCookie.Values.Remove("babka");

// Add the cookie back to the collection (jar)

Response.Cookies.Add(myCookie);

// See what's in the cookie now

Response.Write(myCookie.Values.ToString());



Of course I suppose you used the code we created earlier (the one with the chocolate muffin and the cinnamon babka), therefore if you test the code now you'll see the result is 'muffin=chocolate' - we got rid of the babka!
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Gurjeet Saini on Wednesday, September 7th 2005 at 07:42 AM

Thanks a lot. I solved the problem after reading this article.

by G.Ramesh on Wednesday, September 7th 2005 at 12:24 PM

my problem is set in cookie path .
my path "d:\ramesh\" so using in cookies.path method.
but not save cookie in my path.
please solve my problem after send my mail.
i am waiting for your mail.

by raju on Thursday, July 27th 2006 at 12:57 AM

Good Article

by linda on Monday, September 18th 2006 at 07:11 PM

Thanks for the great article! I spent a day and a half surfing around for C# cookie tutorials. Yours is clear and concise, superior!

thanks

by Varun Arora on Thursday, March 1st 2007 at 08:33 AM

Really good article.
But my problem is this that I have to set the cookie from javascript and then to get it on to code behind on server side.

by Dan on Monday, March 5th 2007 at 04:41 AM

Wondering if anyone can help me?

I amd trying to set a cookie in javascript and the read the cookie back using asp.net!

Anyone got any ideas?

by Lars-Ove Johansson on Friday, May 11th 2007 at 05:56 AM

// Function to remember the login details in a cookie.
function RememberMe()
{
// Get the login data.
var username = document.getElementById('txtUsername').value;
var password = document.getElementById('txtPassword').value;

// Remember the cookie for 100 days from now.
var date = new Date();
date.setTime( date.getTime() + (8640000000) );

// Set the cookie.
document.cookie = "Username=" + username + "; expires=" + date.toGMTString() + "; path=/";
document.cookie = "Password=" + password + "; expires=" + date.toGMTString() + "; path=/";
}

' Read and set the username and password from the cookies.
If IsNothing(Request.Cookies("Username")) = False Then txtUserName.Text = Request.Cookies("Username").Value
If IsNothing(Request.Cookies("Password")) = False Then txtPassword.Text = Request.Cookies("Password").Value

by Malcolm on Tuesday, May 29th 2007 at 05:01 AM

Thanks Andrei, short and sweet, cheers for sharing :-)

by jaiprakash on Thursday, May 31st 2007 at 07:01 AM

coding is very simple & easy to understand.
thanks

by bosebabu on Wednesday, June 6th 2007 at 02:18 AM

short and good

by on Tuesday, June 19th 2007 at 03:45 AM

http://www.geekpedia.com/captcha.php
Verification value

by Prashant on Wednesday, June 27th 2007 at 03:15 AM

dude , i 'm not able to save the cookie ,i did the same thing u mentioned but still its not happn' at my place ,just tell me wht exactly is domain ? , may be that is the thing dats bugging me !!!

by Sunil Dhakne on Wednesday, August 1st 2007 at 09:08 AM

Hi Dude,

Really great resource for the cookies...i really pleased with this.
Thanks

Sunil D

by Nguyen_prince on Tuesday, November 13th 2007 at 11:41 PM

Thanks you !!

by Charles Rex on Friday, November 16th 2007 at 06:06 AM

How to change in JavaScript, the cookie set in C# ?
It doesn't work in your example

Here is this code snippet:

1. I set the cookie in C# Page_Load using the code above

HttpCookie myCookie = new HttpCookie("cakes");
myCookie.Values.Add("muffin", "chocolate");
myCookie.Values.Add("babka", "cinnamon");
Response.Cookies.Add(myCookie);

2.When I press a push button on the web form, on the onclick event I write the following in JavaScript:

var s = document.cookie;
document.cookie = "cakes=Hello";
s = document.cookie;


I see that "s" is the concatenation of the two values, instead of replacing the old value ?!

"cakes=Hello; cakes=muffin=chocolate&babka=cinnamon"




by naufal on Sunday, January 20th 2008 at 01:42 AM

thanx a lot. it helped me a lot

by ridiculous on Monday, February 25th 2008 at 11:10 AM

ASP.NET = BASIC not C#


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs ASP.NET Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons