A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session.
| |
Two types of cookies available in .Net
| |
Non Persistent cookies are stored in memory of the client browser session, when browsed is closed the non persistent cookies are lost.
| |
Below code demonstrates how to create and add in memory cookies.
//Create a Cookie: HttpCookie myCookie = new HttpCookie(“UserId” , “xyz”); //Add Cookie to Response using Add method, shown below. Response.Cookies.Add(myCookie); | |
Persistent Cookies have an expiration date and theses cookies are stored in Client hard drive.
When the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. | |
//Create a Cookie: HttpCookie myCookie = new HttpCookie(“UserId” , “xyz”); //Set Expiration DateTime myCookie.Expires = DateTime.Now.AddDays(7); //Add Cookie to Response using Add method, shown below. Response.Cookies.Add(myCookie); | |
To create a Cookie that never expires, set the Expires property of the Cookie object to DateTime.MaxValue.
myCookie.Expires = DateTime.MaxValue; | |
We can get the cookie value from the Request.Cookies collection
Request.Cookies[“myCookie”].Value. | |
Advantages:
| |
| |
Interview Question on Cookies in ASP.NET
Interview Question on Cookies