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.
1) 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);
2) 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());
3) 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);
4)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";
5) 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).
6) 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);
7) 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");
I hope it will help u aloat..
|
| Author: Kapil Dhawan 18 Jun 2008 | Member Level: Gold Points : 2 |
Hello Nice piece of code Thanks for sharing your knowledge with us. I hope to see more good code from your side This code will help lots of guys Thanks to you Regards, Kapil
|