Sunday, September 21, 2008

how to read and add cookies in .net c#

C# And Cookies
--------------
Cookies allow you to store small bits of data on the user's computer. They take up a small amount of space on the user's hard drive and are often useful for storing nonessential information, such as user preferences.


ReadCoookies.aspx: Reading Cookies Written from the WriteCookies Example
1: <%@ language="C#" %>
2:
23:
24:
25: Use the button below to read a cookie

26:

27: Cookie Name
28:
29:
30: Write Cookies
31:
32:



WriteCookies.aspx: Writing Arbitrary Cookies
1: <%@ language="C#" %>
2:
22:
23:
24:

Use the button below to write cookies to your browser


25: The cookies will expire in one minute.
26:

27: Cookie Name

28: Cookie Value

29:

30:
31: Read the cookies
32:
33:




ReadCookies.aspx page reads cookies stored on a user's browser.

To write a cookie, create a new HttpCookie object (Line 6 of Listing 3.2), assign a string to its Value property (Line 9), and then call the Add() method on the Response.Cookies object (Line 17). You can also set the time of expiration for a cookie by setting the Expires property to a DateTime value (Line 14).

ReadCookies.aspx in Listing 3.3 shows that it's equally easy to read cookies back, using the Request.Cookies collection (Line 9), which is indexed by cookie name.

Cookies can store only strings, so if you need to store a more complex data type, it must be converted into a string. One possibility for storing complicated data structures is to write the structure out as an XML string and convert it back when reading the cookie.

You can store multiple strings in a cookie by treating each cookie as a collection object. For example, the following would work fine:

HttpCookie cookie = new HttpCookie("UserFavorites");
cookie["FavoriteColor"] = "blue";
cookie["FavoriteFlavor"] = "chocolate";
cookie["FavoriteDrink"] = "coffee";



Advanced Properties of the HttpCookie Class
Property
Description

Domain
Gets/sets the domain name that this cookie belongs to. If set, it restricts access to this cookie from Web servers in the specified domain, such as mycompany.com.

Path
Gets/sets the path that this cookie belongs to. If set, it restricts access to this cookie from Web pages in the specified path.

Secure
Gets/sets a flag that tells whether the cookie should be transmitted securely to the client browser using the HTTPS protocol. You must have HTTPS set up on your Web server for this option to work.

HasKeys
Tells whether the cookie is made up of a collection of strings.


No comments: