Basics of Cookies is Asp.Net
Through this article you are able to know about the following points:
1> What are the cookies?
2> How to write and read cookies
3> Limitation of cookies
1>What are cookies?
So, the proper definition of a cookie will be –
Cookies are small text files stored on hard drive of user by web server. They contain information the server can read whenever user visits the site and/or request for a particular page from that site.
2>How to write and read cookies:
a>Create & Set (Write) a cookie:
The two most important things to create a cookie are –
•Give a proper name to the cookie and set its value.
•Set the time of expiration of that cookie
Example:
Let, in a web page there is a textbox named txtUserName and it is used to store name of a user. The following code will help you to create a cookie named userName which contains the text in txtUserName textbox and will expire after 10days of creation.
Response.Cookies("userName").Value = txtUserName.Text.Trim();
Response.Cookies("userName").Expires = DateTime.Now.AddDays(10);
Remember,if user deletes the cookie, then web server will not found it in user’s hard drive even if the cookie will not cross its expiration time.
Alternative way to Create & Set (Write) a cookie:
HttpCookie myCookie = new HttpCookie ("userName");
myCookie.Value = txtUserName.Text.Trim();
myCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(myCookie);
b>Read the value of cookie:
The two most important things to create a cookie are –
•Check whether the value of cookie is null or not.
•Set the value of Cookie in a variable or any other controls like textbox etc.
Example:
Recall the previous example. Now you try to retrieve the username from the cookie “username” and set the value to a textbox named txtClientName of the another webpage of same web server. The code will be as follows:
if (Request.Cookies (“username”) != null)
txtClientName.Text = Request.Cookies(“username”).Value;
Remember, if you do not check whether the cookie is present or not then you’ll get System.NullReferenceException exception when cookie is not present.
Alternative way to Read the value of a cookie:
if (Request.Cookies (“username”) != null)
{
HttpCookie myCookie = Request.Cookies ("userName");
txtClientName.Text = myCookie.Value;
}
3>Limitation of cookies:
•Previously told, user can remove cookies at anytime from their hard drives so the expiration time should not be taken to a standard parameter of a cookie to expire.
•Many users can disable their browser to receive cookies for security reason. In that case use of cookie is meaningless.
•You cannot store large information of user in a cookie as cookies are used to store limited text like User ID or any other small identifiers. Most browsers support 4096 bytes for cookies.