Cookies In ASP.NET

What Is A Cookie

Cookie takes less memory space on the web server that is used to store small data, so basically cookie is a small text file that is created by the web server and saved it by the browser.

It is used to store small amount of data on the browser when someone is visiting a site using the browser. The common purpose to use cookie is to remember the user who has already visited, so it maintains the personal information on the client machine within the browser.

Is This Secured

Sometimes it is also used to authenticate the user information. But cookie can be stolen by hackers because it is a simple text file to store small data. So, it is not secured.

There are two types of cookies:

  1. In Memory Cookie
  2. Persistent Cookie

In Memory Cookie

It is called In Memory Cookie because it is stored inside the browse memory process. It is a temporary cookie and if you close the browser then the cookie gets auto deleted. This cookie data can be accessible to all the pages within the same client request. In C# HttpCookie class is used to send and read the cookie.

  • Create Cookie
    1. HttpCookie MyCookie = new HttpCookie("MyCookie");  
    2. MyCookie.Value = txtSetCookie.Text;  
    3.   
    4. MyCookie.Expires = DateTime.Now.AddHours(1);  
    5. Response.Cookies.Add(MyCookie);  
  • Read Cookie
    1. string cookievalue = Request.Cookies["MyCookie "].Value;  

Persistent Cookie

It is a different type of cookie. It is stored on client hard disk and maintained by the client system that is why it is called persistent cookie.

HttpCookie class contains some list of properties:

  • Expires: It is expiration time of cookie.
  • HasKeys: If the cookie has subkeys than it will be true.
  • Name: It is the name of cookie.
  • Value: It is the value of cookie.

Thanks for reading the article. Hope you enjoyed it.

Up Next
    Ebook Download
    View all
    Learn
    View all