Cookies in ASP.NET

Cookies in ASP.NET

This information is filtered from msdn and some useful sites to make it convenient to read and understand.
Web applications can store small pieces of data in the client side in the form of cookies. A cookie is a small amount of data that is stored at the client side. The most common use of cookies is to identify a single user as he or she visits multiple Web pages.
When a Page is requested, the web application creates a cookie and sends it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request to the same web application.

(1) Creating Cookies

{

      Response.Cookies["userid"].Value = "Suresh";

      Response.Cookies["userid"].Expires = DateTime.Now.AddDays(1);

}

      --- OR ---

{

      HttpCookie cookie1 = new HttpCookie("userinfo");

      cookie1 .Value = "Suresh";

      cookie1 .Expires = DateTime.Now.AddDays(1);

      Response.Cookies.Add(cookie1 );

}


(2) Reading Cookies:

{

      if(Request.Cookies["userName"] != null)

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

}

      --- OR ---

{

      if(Request.Cookies["userName"] != null)

      {

            HttpCookie aCookie = Request.Cookies["userName"];

            Label1.Text = Server.HtmlEncode(aCookie.Value);

      }

}

 

(3) Examples

Example 1:

If a user requests a page, the server 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 along with the requested page, which is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary).

Later, if user requests a page from the same site again, when the user enters the URL the browser checks at client side for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to the site along with the page request. The application site 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.

 

// Check if cookie exists, and display it if it does

if (Request.Cookies["PagelastVisit"] != null)

{

        Label1.Text = Request.Cookies["PagelastVisit"].Value;

}

else

{

        Label1.Text = "No value defined";

}

// Define the cookie for the next visit

Response.Cookies["PagelastVisit"].Value = DateTime.Now.ToString();

Response.Cookies["PagelastVisit"].Expires = DateTime.Now.AddDays(10);

 

Example 2:
Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining continuity in a Web application—that is, of performing state management. Many times, however, it's useful for the Web server to recognize users when they request a page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information.

(4) Modifying Cookies

You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client. The following code example shows how you can change the value of a cookie that stores a count of the user's visits to the site:

EXAMPLE :

{

        int counter;

        if (Request.Cookies["counter"] == null)

            counter = 0;

        else

        {

            counter = int.Parse(Request.Cookies["counter"].Value);

        }

        counter++;

        Response.Cookies["counter"].Value = counter.ToString();

        Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);

}

 

(5) Deleting Cookies

To delete a cookie, overwrite the cookie and set an expiration date in the past. You can't directly delete cookies because they are stored on the client's computer.
EXAMPLE :

Response.Cookies["counter"].Expires = DateTime.Now.AddDays(-1);


(6) Controlling the Cookie Scope

By default, browsers won't send a cookie to a Web site with a different hostname. You can control a cookie's scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:

Example:

Response.Cookies["lastVisit"].Path = "/Application1";

Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server.

(7) Controlling the Cookie Domain Scope

We can expand the scope to a particular domain using the following statement:
Example:
Response.Cookies[“lastVisit”].Domain = “forums.sureshpaldia.com”;

or

Response.Cookies[“lastVisit”].Domain = “wiki.sureshpaldia.com”;


(8) Cookie Limitations:

(1) Browsers can store cookies of up to 4KB. Hence, cookies are best used to store small amounts of data.For eample, the user ID can be stored as cookie and can then be used to identify the user and read user specific information from some data store

(2) Browsers can store maximum 20 cookies per site and if you try to store more, the oldest cookies are discarded.

(3) Users can set their browser to refuse cookies. So, you might have to avoid cookies while storing user-specific information. By default, ASP.NET uses a non-persistent cookie to store the session state. However, if a user has disabled cookies on the browser, session state information cannot be stored in a cookie. ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session IDs not in a cookie, but in the URLs of pages in your site.

(4) Your cookies are subject to examining and spoofing, and therefore should never store sensitive data in a cookie, such as user names, passwords, credit card numbers, and so on.


(9) Storing Multiple Values in a Cookie:

You can store multiple values in a cookie, as the following code demonstrates:
Example:
Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"].Value = "Tony";

Response.Cookies["info"]["border"].Value = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);