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 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 .NETshow 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());
…
Website: dotnetsparkles.files.wordpress.com | Filesize: 252kb
No of Page(s): 5
Click here to download Handling cookies in ASP .NET.
Related Tutorial
Tags: .NET, Cookie Handling
Comments
Leave a Reply