Frequently Asked Interview Questions

Interview Question on Cookies in ASP.NET

Interview Question on Cookies
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
  1. Non Persistent / Session Cookies
  2. Persistent Cookies
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:
  1. Easy to implement.
  2. No server resources are required: The cookie is stored on the client and read by the server after a post.
  3. Simplicity: The cookie is a lightweight, text-based structure with simple key-value pairs.
  4. Cookies can be configured to expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
  1. Size limitations: Most browsers place a 4096-byte limit on the size of a cookie.
  2. Users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
  3. Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail.

Most Visited Pages

Home | Site Index | Contact Us