Set and retrieve cookies in ASP.NET

June 04, 2011 - 12:50

You may wish to set cookies on your webpage which are usefull for things like login areas. This can be done with session variables, but i find those to be less reliable and are regularly cleared when new files are uploaded to the server.

To set a cookie create a new HttpCookie class and assign variables to this.

Dim logincookie As New HttpCookie("Login")
logincookie.values("Email")="test@test.com"
logincookie.values("Password")="password"
Response.Cookies.Add(logincookie)


Once the page is returned to the browser then the cookie is set. Please note that this is only for the current session and after the browser is closed the cookie is removed.

And to read back the cookie use the code below.

Dim email as string
Dim password as string
Dim logincookie As HttpCookie = request.cookies("Login")
email= logincookie.values("email")
password= logincookie.values("password")


If you wish to make the cookie permanent, usefull for those "keep me logged in" options for login areas. Then add the following just before the Response.Cookies.Add(logincookie) line of code.

logincookie.Expires=Dateadd("d",365,Now())


This sets the expiry date for 1 year from now.



© 2011 simplevb.net