Cookies are used to store small amounts of data on the user's browser. This data is limited to 4KB and must be a string.
There are two types of cookies:
Temporary cookies are stored in the browser's memory. You can add a temporary cookie by doing the following:
HttpCookie myCookie = new HttpCookie("MyName", "Gregory MacBeth");
Response.Cookies.AddImyCookie);
Persistent cookies are stored on the hard drive. You can add a permanent cookie by doing the following:
HttpCookie myCookie = new HttpCookie("MyName", "Gregory MacBeth");
myCookie.Expires = DateTime.MaxValue; // Or a specific date
Response.Cookies.AddImyCookie);
The only difference between these two cookie types is that a persistent cookie has an expiration date. Once a cookie is created, it is automatically sent to and from the browser via the HTTP headers. HttpCookie contains some common properties that you can set. These properties are listed in Table 23-9.
|
Key |
Description |
|---|---|
|
Domain |
Indicates the domain associated with the cookie |
|
Expires |
Indicates the expiration date of the cookie |
|
HasKeys(bool) |
Indicates if a cookie contains a dictionary |
|
Name |
Defines the name of a cookie |
|
Path |
Indicates the path associated with a cookie (the default value is /) |
|
Secure |
Indicates if the cookie should be sent over an encrypted connection only |
|
Value |
Stores the value of the cookie |
|
Values |
Named value pair that stores key and value pairs in a dictionary |
You can retrieve a cookie value by using the following code:
Response.Write(Request.Cookies("MyName").Value);
A dictionary allows you to populate a cookie with multiple types of information, ranging from strings to numbers and more.
Here is an example of using a dictionary in a cookie:
HttpCookie myCookie = new HttpCookie("myContactInfo");
myCookie.Values("Name") = "Greg MacBeth";
myCookie.Values("Address") = "111 139th Street.";
myCookie.Values("City") = "Fort Mill";
Response.Cookies.Add(myCookie);
You can read a dictionary cookie via the following code:
if(myCookie.HasKeys = "true")
{
foreach(string Info in myCookie.Values);
{
Response.Write(myCookie.Values("Info));
}
}