Cookies are one of the State Management technique in Asp.Net. By using Cookies we can store data at client side, that means cookies are stored in browser at user machine. Cookies are nothing but text files which are stored at client side. Storing sensitive information by using cookies is not good practise because those are stored at client side, so user can directly read those cookies.
Basically Cookies are two types, Temporary Cookies and Persistent Cookies. Temporary Cookies are key/value pairs stored in HTTP Header rather than user hard disk, that means we will lose the Temporary Cookies once we close the browser. In other hand, Persistent Cookies are also key/value pairs which are stored in user hard disk for specified time, we will not lose the cookie within mentioned time period until we delete the cookie.
In Asp.Net we can create the cookie by using HttpCookie class. Create object for HttpCookie class, provide key and value pair, mention expiry date for persistent cookie and for temporary cookies no need to mention any expiry date, add this object to Response.Cookies as shown below,
///<summary>
/// it creates the cookie
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void btnCreate_Click(object sender, EventArgs e)
{
//create temporary cookie
HttpCookie tempCookie = new HttpCookie(txt1.ID.ToString(), txt1.Text);
Response.Cookies.Add(tempCookie);
//create persistent cookie
HttpCookie perCookie = new HttpCookie(txt1.ID.ToString(), txt1.Text);
perCookie.Expires = DateTime.Parse("1/1/2020");
Response.Cookies.Add(perCookie);
lbl1.Text = "Cookie Added Successfully";
}
We can read Cookie value by using Request class as shown below.
///<summary>
/// it reads the cookie value
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void btnRead_Click(object sender, EventArgs e)
{
if (Request.Cookies[txt1.ID.ToString()] != null)
lbl1.Text = "Cookie Value: " + Request.Cookies[txt1.ID.ToString()].Value;
else
lbl1.Text = "No Data in Cookie";
}
We can easily delete the cookie programmatically by assigning past date to expires value of particular cookie as shown below.
///<summary>
/// it deletes the cookie
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void btnDelete_Click(object sender, EventArgs e)
{
//check whether cookie exists
if (Request.Cookies[txt1.ID.ToString()] != null)
{
HttpCookie perCookie = new HttpCookie(txt1.ID.ToString(), txt1.Text);
perCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(perCookie);
lbl1.Text = "Cookie Deleted Successfully";
}
else
lbl1.Text = "Cookie Not Found";
}
The disadvantages of cookies are we cannot store bulk data, cookies are stored in client machine so storing sensitive information in cookies is not good idea.