Introduction To Cookies in ASP.Net

Introduction

Cookies are a State Management Technique that can store the values of control after a post-back. Cookies can store user-specific Information on the Client's machine like when the user last visited your site. Cookies are also known by many names, such as HTTP Cookies, Browser Cookies, Web Cookies, Session Cookies and so on. Basically cookies are a small text file sent by the web server and saved by the Web Browser on the Client's Machine.

Basically Cookies are one of the following 2 types:

  1. Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text file in the hard disk of the computer.
  2. Non-Persistent Cookies: Non-Persistent cookies are temporary. They are also called in-memory cookies and session-based cookies. These cookies are active as long as the browser remains active, in other words if the browser is closed then the cookies automatically expire.

Now I am showing a practical difference between Persistent and Non-Persistent Cookies with an example.

Step 1: Open Visual Studio 2010.
Step 2: Now go to "New Project" > "Web" > "ASP.NET Empty Web Application".

Empty Web Application

Step 3: Now click on the Solution Explorer.

Solution Explorer

Step 4: Now right-click on "Add" > "New Item" > "Web Form" and add the name of the Web Form.

name of the Web Form

Step 5: After adding the Web Form you will write the following code:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Cookies._Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7.     <style type="text/css">  
  8.         .style1  
  9.         {  
  10.             width: 100%;  
  11.         }  
  12.         .style2  
  13.         {  
  14.             width: 179px;  
  15.         }  
  16.     </style>  
  17. </head>  
  18. <body>  
  19.     <form id="form1" runat="server">  
  20.     <div>  
  21.         <table class="style1">  
  22.             <tr>  
  23.                 <td class="style2">  
  24.                     Welcome To default Page  
  25.                 </td>  
  26.                 <td>  
  27.                        
  28.                 </td>  
  29.             </tr>  
  30.             <tr>  
  31.                 <td class="style2">  
  32.                     User Name  
  33.                 </td>  
  34.                 <td>  
  35.                     <asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>  
  36.                 </td>  
  37.             </tr>  
  38.             <tr>  
  39.                 <td class="style2">  
  40.                     Password  
  41.                 </td>  
  42.                 <td>  
  43.                     <asp:TextBox ID="tbPwd" runat="server"></asp:TextBox>  
  44.                 </td>  
  45.             </tr>  
  46.             <tr>  
  47.                 <td class="style2">  
  48.                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />  
  49.                 </td>  
  50.                 <td>  
  51.                        
  52.                 </td>  
  53.             </tr>  
  54.         </table>  
  55.     </div>  
  56.     </form>  
  57. </body>  
  58. </html> 

Code: This code also shows how to write the cookies.

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     //create a cookie by using HttpCookie class and add the name of the cookie that is Democookie  
  4.     HttpCookie cookie = new HttpCookie("Democookie");  
  5.     //assign the textBoxes Value on introduction-of-cookies  
  6.     cookie["UserName"] = tbUserName.Text;  
  7.     cookie["Pwd"] = tbPwd.Text;  
  8.     //Write the Cookies on the client machine  
  9.    Response.Cookies.Add(cookie);  
  10.    //Redirect the page to other page  
  11.    Response.Redirect("WebForm2.aspx");  

Step 6: Now the WebForm2.aspx Web Form is also added and after the following Code is:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Cookies.WebForm2" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7.     <style type="text/css">  
  8. .style1  
  9. {  
  10. width: 345px;  
  11. }  
  12. .style2  
  13. {  
  14. width: 204px;  
  15. }<a href="WebForm2.aspx">WebForm2.aspx</a>  
  16. </style>  
  17. </head>  
  18. <body>  
  19.     <form id="form1" runat="server">  
  20.     <div>  
  21.         <table class="style1">  
  22.             <tr>  
  23.                 <td class="style2">  
  24.                     Welcome to WebForm2  
  25.                 </td>  
  26.                 <td>  
  27.                        
  28.                 </td>  
  29.             </tr>  
  30.             <tr>  
  31.                 <td class="style2">  
  32.                     User Name  
  33.                 </td>  
  34.                 <td>  
  35.                     <asp:Label ID="lblUname" runat="server"></asp:Label>  
  36.                 </td>  
  37.             </tr>  
  38.             <tr>  
  39.                 <td class="style2">  
  40.                     Password  
  41.                 </td>  
  42.                 <td>  
  43.                     <asp:Label ID="LblPwd" runat="server"></asp:Label>  
  44.                 </td>  
  45.             </tr>  
  46.             <tr>  
  47.                 <td class="style2">  
  48.                        
  49.                 </td>  
  50.                 <td>  
  51.                        
  52.                 </td>  
  53.             </tr>  
  54.         </table>  
  55.     </div>  
  56.     </form>  
  57. </body>  
  58. </html> 

Code: This code will show how to read cookies:

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     //Retrive the Demointroduction-of-cookies on the client's pc  
  4.     HttpCookie cookie = Request.Cookies["Democookie"];  
  5.    if (cookie != null)  
  6.    {  
  7.        //assign the introduction-of-cookies value on the labelk  
  8.       lblUname.Text = cookie["UserName"];  
  9.       LblPwd.Text = cookie["Pwd"];  
  10.    }  

Output

Output
 
From this output are the following 3 important points:
  1. If the same URL is open in a new tab in the same browser then it also provides the same output.
  2. Now when I close the browser and again open the browser and open the same URL then I also don't get the same output, in other words the cookies expire that are the Non-Persistent Cookies.
  3. For Persistent Cookies we need to add the Expiration time of the cookies, in other words the browser manages the time of the cookies and if we close the browser then we also get the same output and the cookie will not expire; they are Persistent Cookies.
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     //create a cookie by using HttpCookie class and add the name of the cookie that is Democookie  
  4.     HttpCookie cookie = new HttpCookie("Democookie");  
  5.     //assign the textBoxes Value on introduction-of-cookies  
  6.     cookie["UserName"] = tbUserName.Text;  
  7.     cookie["Pwd"] = tbPwd.Text;  
  8.     //Write the Cookies on the client machine  
  9.     Response.Cookies.Add(cookie);  
  10.     //add the Expiration Time That is 20 days  
  11.     cookie.Expires = DateTime.Now.AddDays(20);  
  12.     //Redirect the page to other page  
  13.     Response.Redirect("WebForm2.aspx");  

Deleting The Cookies: Cookies cannot be removed directly because it is on the user's computer. So we can delete cookies using:

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

Multivalued Cookies: A single Cookie can store multiple values and those values are like a subkey for a key.

Now I am showing how to write a Multivalued Cookie.

Step 5: The remaining steps are the same and add the code in the code behind in the Default.aspx.

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.    //Write Cookie  
  4.    HttpCookie cookie = new HttpCookie("Democookie");  
  5.    Response.Cookies["userinfo"]["UserName"] = tbUserName.Text;  
  6.    Response.Cookies["userinfo"]["Pwd"] = tbPwd.Text;  
  7.    Response.Cookies.Add(cookie);  
  8.    cookie.Expires = DateTime.Now.AddDays(30);  
  9.    Response.Redirect("WebForm2.aspx");  

Step 6: Now add the code in the Code Behind in WebFrorm2.aspx.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.    //Read the Cookie  
  4.    HttpCookie cookie = Request.Cookies["Democookie"];  
  5.    if (cookie != null)  
  6.    {  
  7.       lblUname.Text=Request.Cookies["userinfo"]["UserName"];  
  8.       LblPwd.Text=Request.Cookies["userinfo"]["Pwd"];  
  9.    }  

Reasons to use Multivalued Cookies:

  1. It is convenient to keep a related subkey that hs same Expiration Time is in a single cookie.
  2. According to cookie limitations, the size of a cookie file is the limit.

Controlling Cookies Scope: For a specific site all the cookies are stored in a client's machine. If the client requests a page of the site then the cookies are sent to the server and it means that every page of the site gets all the introduction-of-cookies. To resolve these problems, we can set the scope of the introduction-of-cookies in 2 ways:

  1. Limit the scope of the cookie on the server: To limit the Cookies Store on the server set the property as in the following:

    cookie.Path = "/Indexpage";

    The path can either be a physical path under the Site Root or a Virtual Path. By using this Path Property we can set the path that all the cookies are available in in the index page.

    For example if your site is called www.xyz.com then the Cookies are created and will be available to the page with the path https://www.xyz.com/Application1/ and the cookies will not be available to the page in other applications, such as https://www.xyz.com/Application2/.
     
  2. By using a domain: By default cookies are stored in the domain. By using the Domain Property we can set the specific subdomain and all the cookies are available on that page only.

    Response.Cookies["Democookie"].Domain = "xyz.com";

List of properties containing the HttpCookies Class:

  1. Domain: Using these properties we can set the domain of the cookie.
  2. Expires: This property sets the Expiration time of the cookies.
  3. HasKeys: If the cookies have a subkey then it returns True.
  4. Name: Contains the name of the Key.
  5. Path: Contains the Virtual Path to be submitted with the Cookies.
  6. Secured:If the cookies are to be passed in a secure connection then it only returns True.
  7. Value: Contains the value of the cookies.

Limitation of the Cookies

  1. The size of cookies is limited to 4096 bytes.
  2. A total of 20 cookies can be used in a single website.

The following describes how to check whether or not the browser accepts cookies.

To check the Browser Capabilitis a property of the HttpRequest class is Request.Browser.Cookies. If it returns true then the browser supports cookies.

  1. //if the request Goes To server  
  2. if (!IsPostBack)  
  3. {  
  4.     // These Property Shows the capability of the Browser.If it returns true then Browser Support Otherwise It goes to else condition  
  5.    if (Request.Browser.Cookies)  
  6.    {  
  7.       //First time the QueryString Value will be null  
  8.       if (Request.QueryString["cookie"] == null)  
  9.       {  
  10.          //write the Cookies  
  11.          HttpCookie cookie = new HttpCookie("TestOfCookie""1");  
  12.          //add the introduction-of-cookies  
  13.          Response.Cookies.Add(cookie);  
  14.          //redirect the same page  
  15.          Response.Redirect("Default.aspx?cookie=1");  
  16.       }  
  17.       else  
  18.       {  
  19.           //On the Second Time QueryString Value is not Null  
  20.          //read the introduction-of-cookies  
  21.          HttpCookie cookie = Request.Cookies["TestOfCookie"];  
  22.          //check that whether the Cookies are enable or disable on client's machine  
  23.         if (cookie == null)  
  24.         {  
  25.           Response.Write("Your Browser Has Disabled The Cookie");  
  26.        }  
  27.    }  
  28. }  
  29.    else  
  30.    {  
  31.       Response.Write("Your Browser Doesn't Support Cookie");  
  32.    }  

Disadvantage of the Cookies

  1. Cookies are stored in the user's computer so the user can change the cookies before the browser is sent to the server.
  2. The sensitive data storage in a cookie are not in the hands of the user. It means that the user's Personal Information Store in a cookie, like user name, password, credit card number or someone who might somehow steal the cookies.
    Security of the Cookies: Cookies are sent between the browser and the server as plain text and the for security we can set the Property Secure but the cookies are transmitted only if the connection uses Secure Sockets Layer (SSL). When the cookies are transferred they are SSL encrypted so that no one can read the Information of the cookie.

Up Next
    Ebook Download
    View all
    Learn
    View all