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
- Response.Cookies["UserID"].Value = txtUserID.Text;
Read/Get a cookie value with Request.Cookies[“COOKIES_NAME HERE”].Value.
Example
- lblUserLoginID.Text = Request.Cookies["UserID"].Value;
Uses of cookies
We use cookies mostly for the following reasons.
- Log-In Information.
- To check the previously logged in or not.
- Cart details in cookies before checkout.
- 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
- Stored in client-side, require less server-side resources.
- Easy to create/write/set.
- Auto deleted as we close the browser or we can set the expiry date.
- Restrict the cookies scope on folder level or domain level.
Disadvantage of Cookies
- Cookies can be deleted by user at any time, so we can not completely rely on cookies.
- Cookies store in user system (computer) as normal text file.
- There is limitation of 4096 bytes (4 KB) for storing the data.
Create/Set/Write the cookies
There are two ways to create cookies,
-
-
- Response.Cookies["UserID"].Value = txtUserID.Text;
-
-
- Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
-
-
-
-
- HttpCookie aCookie = new HttpCookie("LoginDateTime");
- aCookie.Value = DateTime.Now.ToString();
-
-
- aCookie.Expires = DateTime.Now.AddDays(1);
-
-
- 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
- if (Request.Cookies["UserID"] != null)
- {
- lblUserLoginID.Text = Request.Cookies["UserID"].Value;
- }
-
- if (Request.Cookies["LoginDateTime"] != null)
- {
- HttpCookie aCookie = Request.Cookies["userName"];
- lblLoginDateTime.Text = aCookie.Value;
- }
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,
- Path or Folder base.
- Domain base.
Path or Folder based restricted cookies example:
- HttpCookie PurchaseAppCookie = new HttpCookie("PurchaseAppCookie");
- PurchaseAppCookie.Value = "Entered in Purchase " + DateTime.Now.ToString();
- PurchaseAppCookie.Expires = DateTime.Now.AddDays(1);
- PurchaseAppCookie.Path = "/Purchase";
- 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.
- Response.Cookies["currentDomain"].Value = DateTime.Now.ToString();
- Response.Cookies["currentDomain"].Expires = DateTime.Now.AddDays(1);
- 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
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <style type="text/css">
- .auto-style1 {
- width: 140px;
- }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <h2>Sign-In </h2>
- <table style="width: 100%;">
- <tr>
- <td class="auto-style1">User ID.</td>
- <td>
- <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
- </td>
- <td> </td>
- </tr>
- <tr>
- <td class="auto-style1">Password</td>
- <td>
- <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
- </td>
- <td> </td>
- </tr>
- <tr>
- <td colspan="2">
- <asp:Button ID="btnSignIn" runat="server" OnClick="btnSignIn_Click" Text="Sign-In" />
- </td>
- <td> </td>
- </tr>
- </table>
-
-
-
- <p>Login page of Portal and User ID and Login DateTime is stored in cookies.</p>
- </div>
- </form>
- </body>
- </html>
Default.aspx.cs code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void btnSignIn_Click(object sender, EventArgs e)
- {
-
-
- Response.Cookies["UserID"].Value = txtUserID.Text;
-
-
- Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
-
-
-
-
- HttpCookie aCookie = new HttpCookie("LoginDateTime");
- aCookie.Value = DateTime.Now.ToString();
-
-
- aCookie.Expires = DateTime.Now.AddDays(1);
-
-
- Response.Cookies.Add(aCookie);
-
- Response.Redirect("ReadingCookies.aspx");
-
- }
- }
Reading the Cookies
Right click on the project and select Add-->Add New Item and select WebForm.
ReadingCookies.aspx code
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadingCookies.aspx.cs" Inherits="ReadingCookies" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <h2>Values are coming from cookies.</h2>
- <br/>
- <br/>
- Your Login ID:
- <asp:Label ID="lblUserLoginID" runat="server" Text="Label" Font-Bold="true"></asp:Label>
- <br />
- <br />
- Your login date time:
- <asp:Label ID="lblLoginDateTime" runat="server" Text="Label" Font-Bold="true"></asp:Label>
- <div>
-
- </div>
- </form>
- </body>
- </html>
ReadingCookies.aspx.cs code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- public partial class ReadingCookies : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Request.Cookies["UserID"] != null)
- {
- lblUserLoginID.Text = Request.Cookies["UserID"].Value;
- }
-
- if (Request.Cookies["LoginDateTime"] != null)
- {
- HttpCookie aCookie = Request.Cookies["LoginDateTime"];
- lblLoginDateTime.Text = aCookie.Value;
- }
- }
- }
Output
Default.aspx
ReadingCookies.aspx