Here i have tried to explain the Cookie and ways of creating, accessing and deleting cookies.
Introduction
A Cookie is a small text file that is either saved on a client’s hard drive or client’s web browser. It contains site specific information that the server sends to the client along with the page output. The cookies are saved on the client device, and whenever the browser requests for a page, the information in the cookie is sent to the server by the client. The cookie is then read and its value is extracted by the server. Cookies are associated with a Web Site not with a specific page, so the browser and the server will exchange cookie information. Hence, it doesn’t matter which page the user requests from your site.
Required Namespace: System.Web
Advantages of Cookies:
- They work transparently without the user being aware that information needs to be stored.
Disadvantages of Cookies:
- Most browsers support cookies of up to 4096 bytes.
- Most browsers allow only 20 cookies per site; if u try to store more, the oldest cookies are deleted.
- Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.
- Users can set their browser to refuse cookies.
There are two types of Cookies:
- Hard Cookies/Persisting Cookies/Permanent Cookies
- Soft Cookies/Non-Persisting Cookies/Temporary Cookies
Let me explain these types elaborately.
- Persisting Cookies – These cookies are stored in the hard disk of the client’s machine. Their expiry date and time can be configured.
- Non-Persisting Cookies – These cookies are stored in the client browser. As soon as the browser is closed, these cookies are destroyed.
More than one value in a single Cookie
Multiple name value pairs can be stored in a single cookie. Here, the name-value pairs are referred as subkeys. Example : Instead of creating two separate cookies name UserName and EmailId, you can create a single cookie named ganeshji that has the sub-keys UserName and EmailId.
Before accessing the value of the cookie, you should make sure that the cookie exists; if the cookie doesn’t exist, you will get a NullReferenceException exception. The HtmlEncode method was called to encode the contents of the cookie and display it in browser.
Modify Cookies :
A cookie cannot be directly modified. Only the way of modifying it is to create a new cookie with the same name and with new values and then sending the cookie to the browser to overwrite the old version on the client.
Deleting Cookies :
A cookie cannot be directly removed, because the cookie is on the client’s Computer. You can make the browser to delete a cookie for you. Create a new cookie, with the same name as the cookie to be deleted and set the cookies expiration to a date earlier than today. On checking the cookie’s expiration, the browser will discard the outdated cookie.
Default.aspx
<table>
<tr>
<td>
<asp:Label ID="lblUserName" runat="server" Text="User Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmail" runat="server" Text="Email Id"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnCreate" runat="server" Text="Create Cookie" OnClick="btnCreate_Click" />
</td>
<td>
<asp:Button ID="btnDelete" runat="server" Text="Delete Cookie" OnClick="btnDelete_Click" />
</td>
<td>
<td>
</td>
<td>
<asp:Label ID="lblMsg" runat="server"></asp:Label>
</td>
</tr>
</table>
Coding : Default.aspx.cs
protected void btnCreate_Click(object sender, EventArgs e)
{
if (Request.Cookies["ganeshji"] != null)
{
//HtmlEncode encodes the value of a cookie before displaying it in the page
lblMsg.Text = "Existing Cookie's UserName is "+Server.HtmlEncode(Request.Cookies["ganeshji"]["UserName"].ToString())+"
"+" and Email Id is "+Server.HtmlEncode(Request.Cookies["ganeshji"]["EmailId"].ToString());
}
else
{
//Create the Cookie object
HttpCookie obj = new HttpCookie("ganeshji");
//Set a value in it
obj.Values["UserName"] = txtUserName.Text;
//Add another value
obj.Values["EmailId"] = txtEmail.Text;
//This particular cookie's life time is 1 day
obj.Expires = DateTime.Now.AddDays(1);
//Add it to the current web response
Response.Cookies.Add(obj);
lblMsg.Text = "Cookie created successfully.";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (Request.Cookies["ganeshji"] == null)
{
lblMsg.Text = "Cookie doesn't exist.";
}
else
{
//Create the Cookie object
HttpCookie obj = new HttpCookie("ganeshji");
//This particular cookie's expiration is set to a date earlier than today.
obj.Expires = DateTime.Now.AddDays(-1);
//Add it to the current web response
Response.Cookies.Add(obj);
txtUserName.Text = " ";
txtEmail.Text = " ";
lblMsg.Text = "Cookie deleted successfully.";
}
}
Following Snap shows the Cookie Created Message:
If the cookie already exists then the values are shown as follows:
Following Snap shows the Cookie Deleted Message:
Following Snap shows that no more cookie exist for deletion:
Cookies Stored in Client's Browser :
TOOLS->OPTIONS->PRIVACY->SHOW COOKIES
Click on localhost and find out the cookies saved in the Browser
REFERENCE:
http://www.codeproject.com/KB/aspnet/Beginners_Cookies.aspx