Home Articles My Account Messages Tools Join
Tech Blog, ASP.Net, VB.Net, C#.Net, Programming Help, Help Guide
StellarPC.com | How to save & retrieve cookies (ASP.Net)
How to save & retrieve cookies (ASP.Net)
Written by: Justin Rich

How to save & retrieve cookies

Content: Creating and reading from cookies in ASP.Net

The use of cookies can aid you as a website programmer for many reason. For one, it allows you to store information on the client machine to verify or validate that the user has indeed been to your site before and you can store certain types of information to use in their unique user experience. One of the main things this is used for is storing their username or password to the client computer so you can automatically log the user back in. If you're going to be storing their password, you MUST hash it. See my article on 'How to hash passwords for storage' if you're not sure how to do this. You may also want to encrypt the username for security purposes as well. Other things you may want to try to track with cookies could be things such as the user's first name or the last time they logged into the site. This enables you to greet the customer or tell them how long it's been since they last logged on without storing that information in your database... or you may not be using a database for your website to have that ability. Cookies have come a long way in recent years and a lot of new browsers don't like them. Users do have the ability to turn them off completely, so you'll want to either notify them that in order to use the features of your site that use cookies, they'll need to enable them for your site.

To create the cookie object, you need this code:

dim password as String = "YOUR HASHED PASSSWORD"
dim username as String = "YOUR ENCRYPTED USERNAME"

Dim newCookie As HttpCookie = New HttpCookie("Login")
newCookie.Values.Add("UserName", username)
newCookie.Values.Add("Verify", password)
newCookie.Expires = #12/31/2020#
Response.Cookies.Add(newCookie)


This creates a cookie object for your site that is deemed as the Login cookie. The 2 items within that cookie string are the Username and Verify which is used for the password. The next step would be to pull the cookie information back out from the client if it exists and use it. This is done like this:

Dim user As String = Request.Cookies("Login")("UserName")
Dim pass As String = Request.Cookies("Login")("Verify")


This is done much like a multi-dimensional array. You have to specify in the first set of parenthesis the name of the cookie object you created for "Login" and then the actual item in the second. This way, you can have different categorizations of cookie objects stored on the client machine.

For information how to hash values, such as passwords, so they are stored in readable form in your cookie, check out this article: http://www.stellarpc.com/articles/board.aspx?id=29
New Post Next 50 | Previous 50
Post# Subject: Posted By: Time:
New Post Next 50| Previous 50