Cookies are one of state management technique. Sometimes when you open a website it stores a cookie in your computer so that if you revisit the website, it can identify you for some specific needs, for example when you login to any website using your username and password provided to you, Website can ask you to remember password so when you opt this option, it stores your identity to the cookies as a result you no longer need to login again and again. Website automatically reads cookie for your identity and you are logged in. Another example can be a shopping cart, Items can be stored in cookies so the user can come back and continue to his shopping cart.
Cookies are maintained by your web browser and are browser specific. Cookies are very simple to use and implement. Some disadvantages are there in cookies as data is stored in simple text format means its not secure, browser can be set to not accept cookies form web servers, maximum number of cookie storage and size of cookie is limited.
Using Cookies in ASP.NET
(You can download a sample project at the end of this article)
As now I assume that you have basic understanding about cookies or state management. We will take an example in which we store username and his occupation in cookies and then retrieve cookie values.
Create a New Asp.NET website and add a page default.aspx with the following code
In the code you can see HttpCookie class performs all the task related to the cookie from creating it to retrieval of its values. HttpCookie class is available in System.Web namespace that we have defined at the top through using statement.
We have also set the cookie Expiry time that specifies how long it can last in user’s system, after that it will be removed automatically.