Cookies in ASP.NET
In this blog, I’m explaining the concept of cookies in
Cookies provide a way to store user-specific data. Cookies
are known as many names HTTP Cookie, Response Cookie, web Cookie and Browser
Cookie and more. Cookies are one of several ways to store data about web site
visitors during the time when web server and browser are not connected. Cookie
is small text file sent by the web server and stored by the client machine to
hard disk. Cookies may be used for authentication, identification of a user
session, user's preferences, shopping cart contents, or anything else that can
be accomplished through storing text data. The purpose of cookie store
user-specific information with in user system to reduce burden on server.
There are two major types of cookie:
Cookies are stored on your computer hard disk. They stay on your hard disk and can be
accessed by web servers until they are deleted or have expired.
Cookies are saved only your web browser is running. They can
be used by a web server only until you close your browser. They are not saved on your disk. A cookie has expired time expired that
is Non-persistent cookie.
There are following limitations for cookies:
Size of cookies is limited to 4096 bytes.
Total 20 cookies can be used on a single
website; if you exceed this browser will delete older cookies.
End user can stop accepting cookies by browsers,
so it is recommended to check the users’ state and prompt the user to enable
Create a form as given below:
Write the code in webForm1.aspx.cs:
public partial class webForm1 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
protected void btnSave_Click(object sender, EventArgs e)
HttpCookie studentObj = new HttpCookie("StudentInfo");
studentObj.Expires = DateTime.Now.AddMinutes(20);
lblMsg.Text = "Data has been Saved";
protected void btnClear_Click(object sender, EventArgs e)
txtStudentRollNuber.Text = "";
txtStudentName.Text = "";
txtStudentAge.Text = "";
ddlCountry.SelectedIndex = 0;
ddlState.SelectedIndex = 0;
ddlCity.SelectedIndex = 0;
txtStudentPincode.Text = "";
lblMsg.Text = "";
protected void btnRead_Click(object sender, EventArgs e)
HttpCookie readCookie = Request.Cookies["StudentInfo"];
if (readCookie != null)
txtStudentRollNuber.Text = readCookie["RollNumber"];
lblMsg.Text = "";
Run the application:
Fill the data and click save button.
Click Clear button to clear.
Click on Read button: