”Don’t focus on having a great blog. Focus on
producing a blog that’s great for your readers.”- Brian Clark

Create and Retrieve Data From ASP.NET Cookies

24 June 2012

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.

using System.Web;
// Create cookie object
HttpCookie cookie = new HttpCookie("country");
// Set cookie values
cookie.Values.Add("countryName", "United States");
cookie.Values.Add("countryCode", "US");
// 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.

Project Highlight
What Client Says
I’ve Got You Covered
  • Website Design
  • Application Development
  • Database System
  • Search Engine Optimization
  • Web Hosting
  • Graphic Design
  • Logo Design
  • Business Cards
  • Corporate Letterhead
  • Posters/Banners
  • Brochures and Flyers
  • Event Invitations
  • Promotional Products
  • Social Media Marketing
  • E-mail Marketing/Campaign
  • Event Marketing