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:
- Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text file in the hard disk of the computer.
- 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".
Step 3: Now click on the Solution Explorer.
Step 4: Now right-click on "Add" > "New Item" > "Web Form" and add the name of the Web Form.
Step 5: After adding the Web Form you will write the following code:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Cookies._Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title></title>
- <style type="text/css">
- .style1
- {
- width: 100%;
- }
- .style2
- {
- width: 179px;
- }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table class="style1">
- <tr>
- <td class="style2">
- Welcome To default Page
- </td>
- <td>
-
- </td>
- </tr>
- <tr>
- <td class="style2">
- User Name
- </td>
- <td>
- <asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td class="style2">
- Password
- </td>
- <td>
- <asp:TextBox ID="tbPwd" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td class="style2">
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
- </td>
- <td>
-
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Code: This code also shows how to write the cookies.
- protected void Button1_Click(object sender, EventArgs e)
- {
-
- HttpCookie cookie = new HttpCookie("Democookie");
-
- cookie["UserName"] = tbUserName.Text;
- cookie["Pwd"] = tbPwd.Text;
-
- Response.Cookies.Add(cookie);
-
- Response.Redirect("WebForm2.aspx");
- }
Step 6: Now the WebForm2.aspx Web Form is also added and after the following Code is:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Cookies.WebForm2" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title></title>
- <style type="text/css">
- .style1
- {
- width: 345px;
- }
- .style2
- {
- width: 204px;
- }<a href="WebForm2.aspx">WebForm2.aspx</a>
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table class="style1">
- <tr>
- <td class="style2">
- Welcome to WebForm2
- </td>
- <td>
-
- </td>
- </tr>
- <tr>
- <td class="style2">
- User Name
- </td>
- <td>
- <asp:Label ID="lblUname" runat="server"></asp:Label>
- </td>
- </tr>
- <tr>
- <td class="style2">
- Password
- </td>
- <td>
- <asp:Label ID="LblPwd" runat="server"></asp:Label>
- </td>
- </tr>
- <tr>
- <td class="style2">
-
- </td>
- <td>
-
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Code: This code will show how to read cookies:
- protected void Page_Load(object sender, EventArgs e)
- {
-
- HttpCookie cookie = Request.Cookies["Democookie"];
- if (cookie != null)
- {
-
- lblUname.Text = cookie["UserName"];
- LblPwd.Text = cookie["Pwd"];
- }
- }
Output
From this output are the following 3 important points:
- If the same URL is open in a new tab in the same browser then it also provides the same output.
- 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.
- 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.
- protected void Button1_Click(object sender, EventArgs e)
- {
-
- HttpCookie cookie = new HttpCookie("Democookie");
-
- cookie["UserName"] = tbUserName.Text;
- cookie["Pwd"] = tbPwd.Text;
-
- Response.Cookies.Add(cookie);
-
- cookie.Expires = DateTime.Now.AddDays(20);
-
- 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.
- protected void Button1_Click(object sender, EventArgs e)
- {
-
- HttpCookie cookie = new HttpCookie("Democookie");
- Response.Cookies["userinfo"]["UserName"] = tbUserName.Text;
- Response.Cookies["userinfo"]["Pwd"] = tbPwd.Text;
- Response.Cookies.Add(cookie);
- cookie.Expires = DateTime.Now.AddDays(30);
- Response.Redirect("WebForm2.aspx");
- }
Step 6: Now add the code in the Code Behind in WebFrorm2.aspx.
- protected void Page_Load(object sender, EventArgs e)
- {
-
- HttpCookie cookie = Request.Cookies["Democookie"];
- if (cookie != null)
- {
- lblUname.Text=Request.Cookies["userinfo"]["UserName"];
- LblPwd.Text=Request.Cookies["userinfo"]["Pwd"];
- }
- }
Reasons to use Multivalued Cookies:
- It is convenient to keep a related subkey that hs same Expiration Time is in a single cookie.
- 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:
- 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/.
- 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:
- Domain: Using these properties we can set the domain of the cookie.
- Expires: This property sets the Expiration time of the cookies.
- HasKeys: If the cookies have a subkey then it returns True.
- Name: Contains the name of the Key.
- Path: Contains the Virtual Path to be submitted with the Cookies.
- Secured:If the cookies are to be passed in a secure connection then it only returns True.
- Value: Contains the value of the cookies.
Limitation of the Cookies
- The size of cookies is limited to 4096 bytes.
- 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.
-
- if (!IsPostBack)
- {
-
- if (Request.Browser.Cookies)
- {
-
- if (Request.QueryString["cookie"] == null)
- {
-
- HttpCookie cookie = new HttpCookie("TestOfCookie", "1");
-
- Response.Cookies.Add(cookie);
-
- Response.Redirect("Default.aspx?cookie=1");
- }
- else
- {
-
-
- HttpCookie cookie = Request.Cookies["TestOfCookie"];
-
- if (cookie == null)
- {
- Response.Write("Your Browser Has Disabled The Cookie");
- }
- }
- }
- else
- {
- Response.Write("Your Browser Doesn't Support Cookie");
- }
- }
Disadvantage of the Cookies
- Cookies are stored in the user's computer so the user can change the cookies before the browser is sent to the server.
- 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.