A very basic method of creating Cookie in ASP.NET with using HttpCookie. You can read briefly about Cookies at http://msdn.microsoft.com/en-us/library/aa289495(v=vs.71).aspx.
I am creating a HTML Page with 3 Buttons to read, write and remove cookie.
HTML Page
< %@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="read_write_httpcookie_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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:label runat="server" ID="labelName" AssociatedControlID="textFullName">Name:</asp:label><br />
<asp:textbox runat="server" ID="textFullName"></asp:textbox>
</p>
<p>
<asp:button runat="server" ID="Button1" Text="Create / Write Cookie" OnClick="Button1_OnClick" />
</p>
<hr />
<h2>
Read Cookie</h2>
<asp:label runat="server" ID="labelFetchCookie"></asp:label><br />
<asp:button runat="server" ID="Button2" Text="Read Cookie" OnClick="Button2_OnClick" />
<hr />
<h2>
Remove Cookie</h2>
<asp:button runat="server" ID="Button3" Text="Remove Cookie" OnClick="Button3_OnClick" />
</div>
</form>
</body>
</html>
Create Cookie
protected void Button1_OnClick(object sender, EventArgs e)
{
string fullName = textFullName.Text;
HttpCookie cookie = new HttpCookie("ASPXCOOKIE", "defaultValueOfASPXCOOKIE");
cookie["Fullname"] = fullName;
cookie["CurrentDate"] = DateTime.Now.ToString();
cookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(cookie);
}
I am creating a cookie with the name of “ASPXCOOKIE” and added two extra values with Fullname and CurrentDate and cookie will expire in 30 minutes.
Read Cookie
protected void Button2_OnClick(object sender, EventArgs e)
{
HttpCookie httpCookie = Request.Cookies["ASPXCOOKIE"];
if(httpCookie != null)
labelFetchCookie.Text = httpCookie["Fullname"];
else
labelFetchCookie.Text = "Cookie not found";
}
Before we read cookie, I am checking cookie availability and get the Fullname from cookie and write in labelFetchCookie Label.
Remove Cookie
protected void Button3_OnClick(object sender, EventArgs e)
{
HttpCookie httpCookie = Request.Cookies["ASPXCOOKIE"];
if (httpCookie != null)
{
httpCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(httpCookie);
labelFetchCookie.Text = "Cookie removed";
}
}
I use above procedure to remove cookie. Basically I am changing cookie expire from 30 minutes to -1 and re-write the cookie.
I hope it will be helpful.
Your comments are most welcome.
Thank you,
Popularity: 4%







Comments on this entry (4 comments)
Did you like this post? You can share your opinion with us! Simply click here.