Beginner's Guide to ASP.NET Cookies

lakhansin-22735
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 2011 red flag

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.
Download the attached demo project for better understanding.


 Download source code for Beginner's Guide to ASP.NET Cookies

Introduction
First I have written this article for beginners, in this article I have demonstrate how to use ‘Cookies’ in a very simpler way and this will be very helpful to those who has never ever used cookie in their projects. I have done some hands on projects also. Hope I have explained this well and I hope you people will like it.
Please give your suggestions and feedback.



What are Cookies?
A cookie is the term given to describe a type of message that is given to a Web Browser by a Web Server.  The main purpose of a cookie is to identify users and possibly prepare customized Web pages or to save site login information for you.

Why do we need Cookies?
The matter is that the HTTP protocol is “disposable” if so it is possible to be expressed. i.e. each time coming on a page, the user begins all over again, does not matter what will be entered and what changes could be done. Cookie helps to the user was remembered on a site. The user does not need to enter one hundred times the same information from page to a page, and even from session to session, because it is stored on user’s disk. It is possible to get to convenience also that the user can always replace this information at itself on a disk "hurriedly". In cookie other various data also can be stored. For example – it could be user’s login information, page customization related information, quantity of page hits and their time.

Advantages of Cookies
Here, I have list out some of are the main advantages of using cookies in a web application:
It's very simple to use and implement.

  • Browser takes care of sending the data.
  • For multiple sites with cookies, the browser automatically arranges them.

Disadvantages of Cookies
Here, I have list out some main disadvantages of cookies are:

  • It stores data in simple text format, so it's not secure at all.
  • There is a size limit for cookies data (4096 bytes / 4KB).
  • The maximum number of cookies allowed is also limited. Most browsers provide limits the number of cookies to 20. If new cookies come, the old ones are discarded. Some browsers support up to 300.

How to create Cookie?
See the below code, how we create a cookies and add it with a web response.

public static void setCookie(string cookieName, string cookieValue, int expiryDays)
{
   //create a cookie
   System.Web.HttpCookie Cookie = new System.Web.HttpCookie(cookieName);
   //Add values in the cookie
   Cookie.Value = cookieValue;
   //Set cookie expiry date-time.
   Cookie.Expires = DateTime.Now.AddDays(expiryDays);
    //Add the cookie to response object.
   System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
}

Here, we have set cookie persist time by using Datetime class, you can set cookie expiry time to hours, days and years or cookie can be persist for long life.
Persistent cookie can removed manually by the user or it will expire as per the decided time.

How read data from Cookies?
Now it is time to retrieve data from the cookies. Before reading the cookies, first we need to check whether a cookie was found or not. It is always a good practice to check a cookie before reading it, because the browser might have disabled cookies.

public static void getCookie(string cookieName)
{
   //If browser support cookies
  if(Request.Browser.Cookies)
 
   //read a cookie
   public static string getCookie(string cookieName)
    {
            //Get cookie value
            if (System.Web.HttpContext.Current.Request.Cookies[cookieName] != null)
                return System.Web.HttpContext.Current.Request.Cookies[cookieName].Value;
            else
                return string.Empty;
     }
  }
}

Where are Cookies stored in the local hard drive?
Yes, this is one of the interesting things to know to find out cookies in your local drive. First of all, from Explorer Folder Options, select show hidden files and folders.

Now browse into Documents & Settings of the current user and open the cookies folder.


Conclusion
There are many topics to learn about cookies. I have covered just a small portion. Hope this will help all beginners to get familiar with cookies. Download the attached demo project to better understand Cookies.

Please give your feedback and suggestions.


Reference
http://msdn.microsoft.com/en-us/library/ms178194%28v=vs.100%29.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

lakhansin-22735
Full Name: Lakhan Singh
Member Level: Starter
Member Status: Member
Member Since: 6/21/2013 3:50:19 AM
Country: India
Lakhan Singh Tech Lead BeyondKey System Pvt. Ltd. Indore, M.P. India
http://www.dotnetfunda.com
Technical Lead

Login to vote for this post.

Comments or Responses

Posted by: Crazydotnetlover on: 7/2/2013 | Points: 25
Nice article and good explanation i read articles related to cookies before this, But i found this one more helpful then others..

Azad Chouhan
author
http://crazydotnetlover.blogspot.in
Posted by: lakhansin-22735 on: 7/4/2013 | Points: 25
Thanks Azad to sharing your thoughts!
Posted by: Kundan64 on: 7/12/2013 | Points: 25
Very good article.

Login to post response

Comment using Facebook(Author doesn't get notification)