Cookies - Setting and Reading

Introduction

Cookies are one of the simplest ways to persist small pieces of data between requests in ASP.NET, yet they’re often misunderstood or implemented inconsistently. Whether you’re storing user preferences, tracking the last selected database, or managing lightweight session helpers, cookies give you a fast, reliable mechanism without involving server resources. This article walks through the essentials—how to set a cookie, how to read it safely, and how to delete it when it’s no longer needed—using clean, practical VB.NET examples you can drop directly into your application.

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)

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences