Thursday, January 19, 2012


A cookie is used to store small piece of information on client machine.A cookie contains page-specific information that a web server sends to a client along with page output.Cookies are used for sending page specific information because HTTP is a stateless protocol and cannot indicate whether page request coming from the same or different client.You can use cookies to keep track of individual user who access a web page across HTTP connection.

Cookies are saved on the client computer.Cookies can be either temporary or persistent.Temporary cookies also know as session cookies,exist in the memory space of browser.When the browser is closed,all the session cookies added to the browser are lost.A persistent cookie is saved as a text file in the file system of the client computer.

Cookies enable you to store information about a client,session,or application.When a browser request a page,it sends the information in the cookie along with the request information.A web server reads the cookie and extracts its value.

Advantages of Cookies:

1. A cookie is stored on the client computer and can be read by the server after a request for a page is posted.Therefore,no server resource is involved in maintaining the cookie.

2. A cookie is a text based data structure that contains key-value pairs.Therefore ,it is easy to create and manipulate cookie.

3. A cookie can either expire when the browser ends or exist indefinitely on the client computer,subject to the expiration rules on the client.

Limitation of Cookies:

1. Cookies that are stored on client computers have a limited size.Most browsers allow cookie to have up to 4096 bytes in size.Therefore you cannot store a large amount of data in a cookie.

2. Users can temper with cookies because cookies are stored on client computer.

3. Users can disable cookies to prevent from being stored on the hard disk of their computer.If a user denies permission for cookies,an web application cannot store cookies on client computer.

When a user visits your site, you can use cookies to store user information. When the user visits your Web site another time, the application can retrieve the information it stored earlier.

If a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the user's browser gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk.

Later, if user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user or check an expiration date.

Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately.

Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store.

The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.

Response.Cookies["userName"].Value = "Anil";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(3);

HttpCookie cCookie = new HttpCookie("lastVisit");
cCookie.Value = DateTime.Now.ToString();
cCookie.Expires = DateTime.Now.AddDays(3);

The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first cookie, the values of the Cookies collection are set directly. You can add values to the collection this way because Cookies derives from a specialized collection of type NameObjectCollectionBase.

For the second cookie, the code creates an instance of an object of type HttpCookie, sets its properties, and then adds it to the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as part of the constructor.

Reading Cookies

When a browser makes a request to the server, it sends the cookies for that server along with the request. In your ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class. The structure of the HttpRequest object is essentially the same as that of the HttpResponse object, so you can read cookies out of the HttpRequest object much the same way you wrote cookies into the HttpResponse object. The following code example shows two ways to get the value of a cookie named username and display its value in a Label control.

if(Request.Cookies["userName"] != null)
    Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
    HttpCookie aCookie = Request.Cookies["userName"];
    Label1.Text = Server.HtmlEncode(aCookie.Value);

Deleting Cookies

HttpCookie cCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
    cookieName = Request.Cookies[i].Name;
    cCookie = new HttpCookie(cookieName);
    cCookie.Expires = DateTime.Now.AddDays(-3);

protected void Page_Load(object sender, EventArgs e)
    string redirect = Request.QueryString["redirect"];
    string acceptsCookies;

    if(Request.Cookies["TestCookie"] ==null)
        acceptsCookies = "No!";
        acceptsCookies = "Yes!";

        // Delete test cookie.
        Response.Cookies["TestCookie"].Expires =  DateTime.Now.AddDays(-3);
    Response.Redirect(redirect + "?AcceptsCookies=" + acceptsCookies, true);

There are 2 types of cookies:

  1:  Persistent cookies
  2:  Non-persistent cookies

Persistent cookies are stored on your computer hard disk. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired. Persistent cookies are not affected by your browser setting that deletes temporary files when you close your browser.

Non-persistent cookies are saved only while your web browser is running. They can be used by a web server only until you close your browser. They are not saved on your disk. 

No comments: