Hi,
In My last 2 posts I have talked about the overview of cookie and how to read and write with the help of a cookie. In this post I will talk about some of the more advanced work that can be done with cookie in Asp.Net.
Many a time we just don’t want to store some values in cookie but a collection of name value pair in a cookie. Remember that there are many limitations in number of cookies you should use. If we use more number of cookies in our application then the possibility of browser deleting the cookie will increase. Hence we should try and use less number of cookies and utilize a cookie to store maximum amount of data.
In Asp.Net you can store a name value pair in a cookie with the help of subkeys. Using subkeys we cannot only reduce the number of cookies for the site but also the amount of data passed (in request and response) and stored for a site. Here is the syntax to read and write subkeys in cookie.
Response.Cookies["user"]["UserName"] = "Vikram";
Response.Cookies["user"]["lastVisit"] = DateTime.Now.ToString();
Or
HttpCookie aCookie = new HttpCookie("user");aCookie.Values["UserName"] = "Vikram";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
Response.Cookies.Add(aCookie);
We can also read the values of the cookies subkeys for the request object in the same fashion.
One more thing, as said before the cookies are made for an entire site. But many a times we need cookies for files in a particular folder only. We can also limit the scope of a cookie for a particular folder on the server. The limit to a folder is done by the path property of the cookie. We can set the path of the cookie to limit the scope of the same. Here is the code on how to do it.
aCookie.Path = "/vikram";
or
Response.Cookies["lastVisit"].Path = "/ vikram";
The path provided can be either the physical path under the site root or the virtual path to the folder.
Vikram