Cookies are small files that are stored either on the user’s hard drive or in the browser’s memory. Their main purpose is to keep information for later so it can be used for more
Their simplicity makes them useful long time storage on a variety of applications.
However, being simple text files means cookies are an advised solution only when the stored information is not too complex or too private. Also, a
In ASP .NET, the built-in cookie functionality comes with the namespace System.Net. Creating a cookie is fairly easy. The cookie represents an instance of the class HttpCookie. Here’s an example of a cookie with some simple data and properties added to it:
// Creating the cookie.
HttpCookie myCookie = new HttpCookie("LanguageSettings");
// Setting a value in it.
myCookie["Language"] = "English";
// Adding another value.
myCookie["Country"] = "UK";
// Setting the cookie to last 24 hours. Without this setting the cookie
// will disapear once the browser is closed.
myCookie.Expires = DateTime.Now.AddHours(24);
// Adding the cookie to the current web response.
Response.Cookies.Add(myCookie);
In the example above you can see the usage of the Expires property. Here are the other properties available to use:
- Domain – the domain the cookie is associated with;
- HasKeys – boolean value indicating whether the value names and the values are put in separate string arrays;
- HttpOnly – boolean value indicating whether the cookie should not be accessible through client-side script. By default cookies are accessible;
- Name – null by default;
- Path – by default it is the server root;
- SameSite – indicates whether the cookie can be sent with cross-site navigation;
- Secure – boolean value indicating whether SSL must be used to transmit the cookie;
- Shareable – boolean value indicating whether output caching is enabled. By default it is not (the more secure setting);
- Value;
- Values – a collection of values in the Key-Value format.
Retrieving of cookies is done by the cookie’s name:
HttpCookie myCookie = Request.Cookies["LanguageSettings"];
string selectedLanguage;
if (myCookie != null)
{
selectedLanguage = myCookie["Language"];
}
To delete a cookie developers just need to set an expiry date that has already passed:
myCookie.Expires = DateTime.Now.AddDays(-1);
Types of Cookies
There are two main types: persistent and non-persistent (temporary, session cookies).
Persistent cookies have expiration date and are used to collect user data for next visits. Common scenarios are cookies for automatic log-ins or language settings.
Temporary cookies are used to track and transfer data from page to page.
Leave A Comment