Setting a Cookie
To store a value in a cookie, create a new HttpCookie, assign the values you want to persist, set an expiration date, and add it to the response. In this example, the selected database name is saved for ten days so the user doesn’t need to choose it again on each visit.
'save the new db to a cookie
Dim newCookie
As HttpCookie = New HttpCookie("intranet")
newCookie("database") = strDatabase
newCookie.Expires = Now.AddDays(10)
Response.Cookies.Add(newCookie)
Reading a Cookie
When retrieving a cookie, always check whether it exists before accessing its values. If the cookie is present, you can pull the stored value and use it to initialize session state or other application logic. If it’s missing, fall back to a default value to keep the application stable.
'retrieve the database from a cookie
If Not Request.Cookies("intranet") Is Nothing Then
Session("database") = Request.Cookies("intranet")("database")
Else
Session("database") = "NGB01"
End If
Deleting a Cookie
To remove a cookie, simply overwrite it with a new one that has an expiration date in the past. This instructs the browser to clear it immediately. This pattern is useful for logout workflows, “Remember Me” toggles, or any scenario where persisted state should be reset.
Dim newCookie As New HttpCookie("RememberMe")
newCookie.Expires = Now.AddDays(-1)
Response.Cookies.Add(newCookie)