Cookies in ASP.NET 4.0
Cookies are one of the State Management techniques, so that we can store information for later use. Cookies are small files that are created in the web browser’s memory (if they’re temporary) or on the client’s hard drive (if they’re permanent).
Cookies are one of the State Management techniques, so that we can store
information for later use. Cookies are small files that are created in the web
browser's memory (if they're temporary) or on the client's hard drive (if
One advantage of cookies is that they work transparently without the user being
aware that information needs to be stored. They also can be easily used by any
page in your application and even be retained between visits, which allows for
truly long-term storage.
They suffer from some of the same drawbacks namely, they're limited to simple
string information, and they're easily accessible and readable if the user finds
and opens the corresponding file. These factors make them a poor choice for
complex or private information or large amounts of data.
Also Some users disable cookies on their browsers, which will cause problems for
web applications that require them. Also, users might manually delete the cookie
files stored on their hard drives. But for the most part, cookies are widely
adopted and used extensively on many websites.
easily work with the appropriate types:
Cookies are fairly easy to use. Both the Request and Response objects (which are
provided through Page properties) provide a Cookies collection. The important
trick to remember is that we retrieve cookies from the Request object, and we
set cookies using the Response object.
To set a cookie, just create a new HttpCookie object. we can then fill it with
and attach it to the current web response:
Create the cookie object.
HttpCookie cookie =
// Set a value in it.
// Add another value.
// Add it to the current web response.
A cookie added in this way will persist until the user closes the browser and
will be sent with every request. To create a longer-lived cookie, you can set an
cookie lives for one year.
we retrieve cookies by cookie name using the Request.Cookies collection:
cookie = Request.Cookies["CookieName"];
// Check to see whether a cookie was found with this
if (cookie != null)
language = cookie["Language"];
The only way to remove a cookie is by replacing it with a cookie that has an
expiration date that has already passed. This code demonstrates the technique:
cookie = new
cookie.Expires = DateTime.Now.AddDays(-1);
A Cookie Example
I have attached an Example that shows how to Set and Reset Cookies. To try this
example, begin by running the page, entering a value, and clicking the Set
Cookie button. Then, close the browser (or click refresh button), and request
the page again. The second time, the page will find the cookie, read the value,
Refresh the Page Again!