What are ASP.NET Cookies? The start point for beginners

h-educate cookies asp

 What are Cookies?

Simply Cookies are small files stored in the client’s system or browser.

So with cookies, we can store some data on the client’s machine and make use of them on our websites. information like users data, authentication data, or maybe a shopping cart.

Cookies work transparently with the user. It can be easily used anywhere in your web application.

As a small idea on how cookies work, the server sends cookies to the client browser to store it. The browser then returns the cookie to the server the next time the page is requested.

cookies heducate


Advantages of Cookies

  • It’s very simple to use.
  • The browser takes care of sending the data.
  • The browser will automatically arrange cookies for multiple sites.

Disadvantages of Cookies

  • There is a size limit for cookies data (4096 bytes / 4KB).
  • The maximum number of cookies allowed is also limited. Most browsers provide limits the number of cookies to 20. If new cookies come, the old ones are discarded. Some browsers support up to 300.
  • We need to enable cookies in the browser from them to work. Cookies will not work on a high-secure configuration of your web browser.


Working with cookies in ASP.NET

How to create Cookies

System.Web namespace must be imported to work with cookies.

The following sample codes shows you how to create a cookie in different methods:


HttpCookie StudentCookies = new HttpCookie("Cookie1");
StudentCookies.Value = "YourValue";
StudentCookies.Expires = DateTime.Now.AddHours(1);


Response.Cookies["Cookie1"].Value = TextBox1.Text;
Response.Cookies["Cookie1"].Expires = DateTime.Now.AddDays(1);

Reading/Getting Cookies

string value = Request.Cookies["Cookie1"].Value;

Deleting Cookies

if (Request.Cookies["Cookie1"] != null)
    Response.Cookies["Cookie1"].Expires = DateTime.Now.AddDays(-1);

Working with cookies in javascript.

Set a cookie

document.cookie = “CookieName=Value; expires=Thu, 18 Dec 2019 12:00:00 UTC; domain=””;path=/”;

For more infor about cookies you can check th following link:



What are persistent and non-persistent Cookies?


Persistent cookies:  permanent cookies.

They are stored in the client hard-drive until they expire (expiration date reaches). Persistent cookies should be set with an expiration date. Sometimes they stay until the user deletes the cookies.

Non-persistent Cookies: temporary Cookies.

If there is no expiration time defined, then the cookie is stored in the browser memory. and will be deleted when the browser closes.

How to make persistent Cookies?

As I told you, simple if you set an expiration date for the cookie it will be persistent till that date:

HttpCookie StudentCookies = new HttpCookie("Cookie1");
StudentCookies.Value = "YourValue";
StudentCookies.Expires = DateTime.Now.AddHours(1);



Sharing is caring!

Leave a Comment

Your email address will not be published. Required fields are marked *