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 Andrew Pociu (View Profile)
*****   (Rated 4.4 with 139 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#

by Teju on Thursday, August 14th 2008 at 11:10 AM

How to read a cookie in a subdoamin site.
Say I have a site url like
https://xyz/login?jumpto=https://abc/home.aspx??

by teju on Thursday, August 14th 2008 at 11:30 AM

Sorry I had not completed my question previously

Say I have a site url like
https://xyz/login?jumpto=https://abc/home.aspx??

I want to read cookies set by url (https://xyz/login.aspx) in the website
(https://abc/home.aspx) in vb.net

Can any one please help me out with this.

Thanks in advance.

by shreen on Saturday, August 23rd 2008 at 10:55 AM

thanks alot i don't know why the cookies not retrieve back throw textbox and checkbox
when i click to the button it will create cookies and the system will check if the checkbox it checke to remember cookies
Dim mycookie As New HttpCookie("EmployeeLogin")

If chkRememberMe.Checked Then
mycookie.Value = Me.txtLoginName.Text
Response.Cookies.Add(mycookie)
Else
esponse.Cookies.Remove"EmployeeLogin")
End If

when the page is load then i check the textbox if it empty or not
but i don't know the cookies not save in my webapplication


If Not Page.IsPostBack Then
Dim LoginCookie As HttpCookie = Response.Cookies("EmployeeLogin")

If LoginCookie.Value <> "" Then
txtLoginName.Text = LoginCookie.Value.ToString
chkRememberMe.Checked = True
Else

chkRememberMe.Checked = False

End If

End If

i need ur help

by Aniket on Monday, October 13th 2008 at 03:09 AM

Really a good and helpful article

by Jo Al on Monday, October 20th 2008 at 06:18 PM

Good article. I understand the key/value pairs (muffin=chocolate, babka=cinnamon, etc.) but what the heck is "cakes"? What is its data type? Is that the cookie's name (string)? What is it used for?

by ayi chan on Wednesday, April 1st 2009 at 10:16 PM

i love cookies
thx for the article it shows me how to bake, store and eat the cookie

by iyrin on Monday, May 25th 2009 at 02:42 AM

i understood cookies well.

by iyrin on Monday, May 25th 2009 at 02:43 AM

i need more explanation on remember me checkbox using cookies

by amudhu on Friday, June 12th 2009 at 07:54 AM

nice tutorial.. great

by on Friday, August 21st 2009 at 04:33 AM

by on Friday, August 21st 2009 at 04:33 AM

by on Friday, August 21st 2009 at 04:33 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Friday, August 21st 2009 at 04:34 AM

by on Thursday, December 3rd 2009 at 08:25 AM

by on Thursday, December 3rd 2009 at 08:25 AM

by on Thursday, December 3rd 2009 at 08:25 AM

by on Thursday, December 3rd 2009 at 08:25 AM

by sheik on Monday, December 7th 2009 at 09:54 PM

my name is sheik i had a great experience

by Deven on Tuesday, February 9th 2010 at 02:37 AM

Best Tutorial!
keep on adding more tutorials pls!

by dheeraj on Saturday, May 29th 2010 at 08:56 AM

hhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiii

by Gousepasha on Thursday, June 10th 2010 at 06:41 AM

Hi,

I can't understand clearly, put some more information.


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 >>
Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons