Saturday, February 12, 2005

ASP.NET Cookies

A cookie is a small piece of data that is created in the server and stored in a client's web browser. Cookies are part of the request data that sent to the server. And server are able to retrieve or update cookies.

Cookie is used in ASP.NET to do the authentication and session tracing. Cookie can be easily manipulated in your ASP.NET web application, such as storing user preferences. It's a good practice to only store small piece of data inside cookie because browsers have cookie size limit. For example, IE has 4K of maximum size of cookie, and only allows 20 cookies per domain name.

To read a cookie, you get the HttpCookie collection from the Request object:
HttpCookie cookie = Request.Cookies["MyCookie"]; // Or Request.Cookies[0]
string cookieName = cookie.Name; // = "MyCookie"
string cookieValue = cookie.Value;
To set or update a cookie:
HttpCookie cookie = new HttpCookie("MyCookie");
cookie.Value = "My Value";
Response.Cookies.Add(aCookie);
Or simply:
Response.Cookies["MyCookie"].Value = "My Value";
To delete a Cookie, you have to update the cookie with expiration defined before current time:
Response.Cookies["MyCookie"].Expires = DateTime.Now.AddDays(-1);
Cookie with expiration time tells browser to remove the cookie when it's expired. A cookie without expired time is called non-persistent cookie because it won't store in user's hard disk, and the cookie is discarded when browser is closed. By default, Session cookie in ASP.NET is non-persistent cookie, while authentication cookie is persistent cookie.

Domain is another property you can set for a cookie. You may have a website of http://www.mysite.com and have a subdomain of http://sales.mysite.com. If you want to share the cookie in these two domains then you should do:
cookie.Domain = "mysite.com";
You can also limit the cookie to a folder in your application by setting cookie's Path property. For example, you want to have a cookie only available in http://www.mysite.com/Application1 and another cookie only available for http://www.mysite.com/Applicaiton2:
cookie1.Path = "/Application1";
cookie2.Path = "/Application2";
You can store one value in a cookie as described above. You can also store multiple name-value pairs in a single cookie:
Response.Cookies["MyCookie"]["Name1"] = "value1";
Response.Cookies["MyCookie"]["Name2"] = "value2";
To get a multi-value cookie:
string cookieValue1 = Request.Cookies["MyCookie"]["Name1"];
string cookieValue2 = Request.Cookies["MyCookie"]["Name2"];
Just for your curiosity, the multi-value cookie transferred between browser and server is something like:

Cookie: MyCookie=Name1=value1|Name2=value2;