tabs

Friday, November 8, 2013

Cookies in ASP.NET

What is a Cookie?

Cookies in .Net are mainly used for state management. Cookies are simple files of plain text which are stored on the client’s hard disk or on browser memory. These files hold the information of the user and uses whenever required.
We all know that HTTP protocols are stateless, In order to achieve state management cookies are used to store small pieces of information on client's system which the webpage is able to read when the user visits that site.Let us see about cookies in detail.

How are Cookies originated?

  1. When the client requests for a page to the server for the first time, the server serves the client along with a cookie. The server generates a session id and sends it to the client as a cookie.
  2. The cookie with the session id is stored on client’s machine or in the browser memory.
  3. Now whenever the same client requests the server, it uses the session id to recognize the client and serves it.
  4. Only the browser and the server are involved in exchanging the cookies.
  5. When you hit an URL to the server, it first checks across the cookies for any information related to it and if present, it is moved to the server with that information.
Simply to tell, Cookies are used to store the information on the client’s system. It contains the information which can be read by the webpage requested whenever the user visits the site.

Types of Cookies:

Cookies are classifies into two types. They are,
  1. Persistent cookies.
    Persistent cookies are also called permanent cookies. These are stored on the client’s hard disk. But it is mandatory to define an expiry date for persistent cookies. Sometimes they live till the user deletes them.
  2. Non-Persistent cookies.
    Non-Persistent cookies can be called as temporary cookies. These reside on the browser memory. No expiry date is defined for these type of cookies.

Creating a Cookie:

 //Create a cookie object
        HttpCookie userDetails_Cookie = new HttpCookie("User_Details");
        //Set values inside the cookie
        userDetails_Cookie["UserName"= "Jimmy";
        userDetails_Cookie["Location"= "Texas";
        //Add the cookie to the curent web response
        Response.Cookies.Add(userDetails_Cookie);

Reading values from a Cookie:

  //Retrieving cookies across the cookie name
        HttpCookie userDetails_Cookie = Request.Cookies["User_Details"];
        string usernamelocation;
        //Checking whether the cookie existed or not
        if (userDetails_Cookie != null)
        {
            username = userDetails_Cookie["UserName"];
            location = userDetails_Cookie["Location"];
        }
Hence here we came to know what exactly a cookie is? And an idea on how do we a cookie is generated and how to write and read values from the cookie.
Hope it helps you and feel free to suggest and post comments if you have any doubts regarding.

No comments:

Post a Comment