What Are Cookies?
Cookies are small text files that are created to store temporary data on the client's browser. Since cookies store data in plain text format (everybody can easily read it), they're not considered as suitable media to store confidential information.
Most browsers support cookies of up to 4 KB. That is quite large space to store user's information, but don't store a big chunk of data in cookies. Practically you store user ID on a cookie and retrieve that user ID to look up user details from the database.
How To Create Cookies?
In the following example, we store user's country preference in a cookie.
// Create cookie object
HttpCookie cookie = new HttpCookie("country");
// Set cookie values
cookie.Values.Add("countryName", "United States");
// Set cookie expiration time to 3 months
cookie.Expires = DateTime.Now.AddMonths(3);
// Add cookies to current web response
How To Retrieve Data From Cookies?
The next time that user visit the website, he doesn't have to select his country preference again. Instead, we pull the data from the cookie.
// Retrieve the cookie by name
string country = string.Empty;
if (Request.Cookies["country"] != null)
country = Request.Cookies["country"].Value;
// Manual country selection
About Site by Tommy
Freelance web design and developer in Jakarta and Microsoft Certified Professional with five years of experience in web design and development, application development, database system, Search Engine Optimization (SEO), graphic design, logo design, business cards, corporate letterhead, posters/banners, brochures and flyers, social media marketing, and email marketing/campaign.