How to use cookies in ASP.NET
Cookies are small text files which are stored on the user hard disk by a browser.Cookies are normally used to identify a user or his preferences such as username or id.When ever the website is opened by the user it checks for the specific cookie.Cookies are not deleted even after browser is closed.We can not store large data in the form of cookies but we can make use of the small cookie data to retrieve the specific information about the user from database.Let’s examine Asp.Net with it’s cookies features.
1.Design a form similar to the one shown in the following image.We will implement the cookies in our simple login form with a Remember Me checkbox.
2.Now double-click on the login button to jump in the code behind section and write the following code.This code generates a cookie if the Remember me checkbox is checked.name is the name of the cookie which is being created on the user computer.cookie.Value = TextBox1.Text; is assigning the value from the textbox to the cookie named name.cookie.Expires =DateTime.Now.AddMonths(1); is setting the expiry date of the cookie in this case our cookie will expire after a month from its creation ,Remember setting the expiry date is must otherwise the cookie will expire when the browser is closed.Response.Cookies.Add(cookie); is finally creating the cookie on the hard drive.
3.Now double-click on the page and write the following code on the page_load event handler.This time we are requesting a cookie from the user hard drive if present.The cookie which is requested is name as we set in previous section.Request.Cookies["name"]; is requesting the cookie and the retrieved cookie is assigned to the cookie variable.If there is no cookie named name is present in the user hard drive than label2 will show Welcome new visitor message.
4.Now run the application ,Notice the Welcome new visitor message appears because we have not yet set the cookie.Now write a username and check the Remember Me checkbox and click login button,we have created our cookie now.
5.Now close the browser and re-run the application, Finally You can see there is no more Welcome new visitor message and the username is automatically picked from the cookie.
This is a very simple cookie example.Cookies can have multiple values and can be more complex but just to make your concept clear, i think this is a good enough example.In case of any query you can make use of comments section.