Today we explain how to create, read and delete cookies in Asp.Net C#.
Advantages of Cookie:
- Its clear text so user can able to read it.
- We can store user preference information on the client machine.
- Its easy way to maintain.
- Fast accessing.
Disadvantages of Cookie
- If user clear cookie information we can't get it back.
- No security.
- Each request will have cookie information with page.
Example :
Aspx page snippet
Enter Name : <asp:TextBox ID="txtName" runat="server" />
<br />
<br />
Your Name : <asp:Label ID="lblName" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="btnCreate" Text="Create Cookie" runat="server" OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" Text="Read Cookie" runat="server" OnClick="btnRead_Click" />
<asp:Button ID="btnDelete" Text="Delete Cookie" runat="server" OnClick="btnDelete_Click" />
Create cookies on create button click
protected void btnCreate_Click(object sender, EventArgs e)
{
//Create a Cookie with a suitable Key.
HttpCookie nameCookie = new HttpCookie("Name");
//Set the Cookie value.
nameCookie.Values["Name"] = txtName.Text;
//Set the Expiry date.
nameCookie.Expires = DateTime.Now.AddDays(30);
//Add the Cookie to Browser.
Response.Cookies.Add(nameCookie);
txtName.Text = "";
lblName.Text = "";
}
Read cookies on read button click
protected void btnRead_Click(object sender, EventArgs e)
{
//Fetch the Cookie using its Key.
HttpCookie nameCookie = Request.Cookies["Name"];
//If Cookie exists fetch its value.
string name = nameCookie != null ? nameCookie.Value.Split('=')[1] : "undefined";
lblName.Text = name;
}
Delete cookies on delete button click
protected void btnDelete_Click(object sender, EventArgs e)
{
//Fetch the Cookie using its Key.
HttpCookie nameCookie = Request.Cookies["Name"];
//Set the Expiry date to past date.
nameCookie.Expires = DateTime.Now.AddDays(-1);
//Update the Cookie in Browser.
Response.Cookies.Add(nameCookie);
txtName.Text = "";
lblName.Text = "";
}