Overview Of Cookies In ASP.NET

In this article, you will get the answer to the following questions.

  • What is a cookie?
  • What are the uses of cookies?
  • What are the types of cookies?
  • Advantages and disadvantages of cookies.
  • How to create/set/write the cookies?
  • How to read the cookies?
  • How to restrict the scope of cookies?
  • Sample code for using cookies.

Cookies

Cookies are one of the client-side state management players, which store the data at the client side. Mostly, 4096 bytes per cookie can be stored. Storing the data client side means it stores them in the client's web browser or hard disk.

Cookies start to work when a user requests a page from your site or enters the URL in the browser. The browser looks for cookies in the local hard disk, associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request.

You will get more interesting facts about cookie limitations.

Defining/Creating/Setting a cookie with Response.Cookies[“COOKIES_NAME HERE”].Value

Example

  1. Response.Cookies["UserID"].Value = txtUserID.Text;  
Read/Get a cookie value with Request.Cookies[“COOKIES_NAME HERE”].Value.

Example
  1. lblUserLoginID.Text = Request.Cookies["UserID"].Value;  
Uses of cookies

We use cookies mostly for the following reasons.
  1. Log-In Information.
  2. To check the previously logged in or not.
  3. Cart details in cookies before checkout.
  4. Conducting a poll.

Types of cookies

There are two types of cookies.

  • Persistent Cookies
  • Non-Persistent Cookies

Persistent Cookies

Cookies are stored on your computer hard disk. The data stays in your hard disk and can be accessed by web servers unless the cookies are deleted or have expired.

Non-persistent Cookies

If you don’t set expiry property of cookies, those cookies are called Non-persistent Cookies. Cookies are saved in web browser and remain till the browser is running.

Advantages and disadvantage of cookies

Advantage of Cookies

  1. Stored in client-side, require less server-side resources.
  2. Easy to create/write/set.
  3. Auto deleted as we close the browser or we can set the expiry date.
  4. Restrict the cookies scope on folder level or domain level.

Disadvantage of Cookies

  1. Cookies can be deleted by user at any time, so we can not completely rely on cookies.
  2. Cookies store in user system (computer) as normal text file.
  3. There is limitation of 4096 bytes (4 KB) for storing the data.

Create/Set/Write the cookies

There are two ways to create cookies,

  1. //First way to create cookies   
  2.         //Assigning the TextBox called txtUserID value into cookies called UserID.  
  3.         Response.Cookies["UserID"].Value = txtUserID.Text;  
  4.           
  5.         //Assigning the expiry of cookies called UserID.  
  6.         Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);  
  7.   
  8.   
  9.   
  10.      //Second way to create cookies  
  11.         HttpCookie aCookie = new HttpCookie("LoginDateTime");  
  12.         aCookie.Value = DateTime.Now.ToString();  
  13.           
  14.         //Added Expiry of cookies  
  15.         aCookie.Expires = DateTime.Now.AddDays(1);  
  16.           
  17.         //Added cookies   
  18.         Response.Cookies.Add(aCookie);  
Read the cookies

While reading the cookies, you should always check the null or not null, otherwise an exception can be thrown on the page.

Example
  1. if (Request.Cookies["UserID"] != null)  
  2.      {  
  3.          lblUserLoginID.Text = Request.Cookies["UserID"].Value;  
  4.      }  
  5.   
  6.      if (Request.Cookies["LoginDateTime"] != null)  
  7.      {  
  8.          HttpCookie aCookie = Request.Cookies["userName"];  
  9.          lblLoginDateTime.Text = aCookie.Value;  
  10.      }  
Restrict the scope of cookies

Basically, restriction is required on cookies because all the cookies for a site are sent to the Server.

We scope the cookies in the  following ways,
  1. Path or Folder base.
  2. Domain base.

Path or Folder based restricted cookies example:

  1. HttpCookie PurchaseAppCookie = new HttpCookie("PurchaseAppCookie");  
  2. PurchaseAppCookie.Value = "Entered in Purchase " + DateTime.Now.ToString();  
  3. PurchaseAppCookie.Expires = DateTime.Now.AddDays(1);  
  4. PurchaseAppCookie.Path = "/Purchase";  
  5. Response.Cookies.Add(PurchaseAppCookie);  
In the above code, cookies are available only to those pages which have the  path of “PURCHASE” folder.

Domain based restricted cookies.
  1. Response.Cookies["currentDomain"].Value = DateTime.Now.ToString();  
  2. Response.Cookies["currentDomain"].Expires = DateTime.Now.AddDays(1);  
  3. Response.Cookies["currentDomain"].Domain = "www.c-sharpcorner.com";  
In the above code, cookies are available only to this domain called “www.c-sharpcorner.com”. 

Sample code of using cookies

Create a new empty web site project named “CookiesExample”.



Right click on the project and select Add-->Add New Item and select WebForm.



Add a new Web Form named “Default.aspx”. In this page, we will be accepting user id and password as well as creating cookies.



Default.aspx code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         .auto-style1 {  
  10.             width: 140px;  
  11.         }  
  12.     </style>  
  13. </head>  
  14. <body>  
  15.     <form id="form1" runat="server">  
  16.     <div>  
  17.         <h2>Sign-In </h2>  
  18.         <table style="width: 100%;">  
  19.             <tr>  
  20.                 <td class="auto-style1">User ID.</td>  
  21.                 <td>  
  22.                     <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>  
  23.                 </td>  
  24.                 <td> </td>  
  25.             </tr>  
  26.             <tr>  
  27.                 <td class="auto-style1">Password</td>  
  28.                 <td>  
  29.                     <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>  
  30.                 </td>  
  31.                 <td> </td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td colspan="2">  
  35.                     <asp:Button ID="btnSignIn" runat="server" OnClick="btnSignIn_Click" Text="Sign-In" />  
  36.                 </td>  
  37.                 <td> </td>  
  38.             </tr>  
  39.         </table>  
  40.   
  41.   
  42.   
  43.         <p>Login page of Portal and User ID and Login DateTime is stored in cookies.</p>  
  44.     </div>  
  45.     </form>  
  46. </body>  
  47. </html>  
Default.aspx.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class _Default : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.     }  
  13.     protected void btnSignIn_Click(object sender, EventArgs e)  
  14.     {  
  15.         //First way to create cookies   
  16.         //Assigning the TextBox called txtUserID value into cookies called UserID.  
  17.         Response.Cookies["UserID"].Value = txtUserID.Text;  
  18.   
  19.         //Assigning the expiry of cookies called UserID.  
  20.         Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);  
  21.   
  22.   
  23.   
  24.         //Second way to create cookies  
  25.         HttpCookie aCookie = new HttpCookie("LoginDateTime");  
  26.         aCookie.Value = DateTime.Now.ToString();  
  27.   
  28.         //Added Expiry of cookies  
  29.         aCookie.Expires = DateTime.Now.AddDays(1);  
  30.   
  31.         //Added cookies   
  32.         Response.Cookies.Add(aCookie);  
  33.   
  34.         Response.Redirect("ReadingCookies.aspx");  
  35.   
  36.     }  
  37. }   
Reading the Cookies

Right click on the project and select Add-->Add New Item and select WebForm.





ReadingCookies.aspx code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadingCookies.aspx.cs" Inherits="ReadingCookies" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.         <h2>Values are coming from cookies.</h2>  
  12.         <br/>  
  13.         <br/>  
  14.         Your Login ID:  
  15.         <asp:Label ID="lblUserLoginID" runat="server" Text="Label" Font-Bold="true"></asp:Label>  
  16.         <br />  
  17.         <br />  
  18.         Your login date time:  
  19.         <asp:Label ID="lblLoginDateTime" runat="server" Text="Label" Font-Bold="true"></asp:Label>  
  20.     <div>  
  21.       
  22.     </div>  
  23.     </form>  
  24. </body>  
  25. </html>  
ReadingCookies.aspx.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class ReadingCookies : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.         if (Request.Cookies["UserID"] != null)  
  13.         {  
  14.             lblUserLoginID.Text = Request.Cookies["UserID"].Value;  
  15.         }  
  16.   
  17.         if (Request.Cookies["LoginDateTime"] != null)  
  18.         {  
  19.             HttpCookie aCookie = Request.Cookies["LoginDateTime"];  
  20.             lblLoginDateTime.Text = aCookie.Value;  
  21.         }  
  22.     }  
  23. }   
Output

Default.aspx



ReadingCookies.aspx


Similar Articles