16.15 Writing and Reading Cookies

 <  Day Day Up  >  

You want to store data locally on a connecting client's machine.


Technique

You write and read cookies within the .NET Framework by using the HttpCookie class. Cookies are stored in a HttpCookieCollection object accessed by the Cookies property in either the Request or Response object. When reading cookies, use the collection defined in the Request object, and when writing, use the Response object. To write a new cookie to a user 's system, create a new HttpCookie object, passing two strings denoting the key and value of each cookie. If you don't set an expiration date, the cookie is removed after the user's session ends. To create an expiration date, set the Expires property equal to a DateTime object, specifying the date when the cookie is invalid, as shown in the following code:

 
 private void btnSubmit_Click(object sender, System.EventArgs e) {     HttpCookie cookie = new HttpCookie( "Name", tbName.Text );     // cookie expires 1 year from now     DateTime dt = DateTime.Now;     TimeSpan ts = new TimeSpan( 365, 0, 0, 0, 0 );     cookie.Expires = dt.Add(ts);     Response.Cookies.Add(cookie);     lblHello.Text = "Hello " + tbName.Text + "! Welcome back!";     tbName.Visible = false;     btnSubmit.Visible = false; } 

Reading a cookie from a Request object is simply a matter of accessing a dictionary-based collection. The Cookies property contains an indexer, allowing you to pass the name of the cookie to retrieve the value. An HttpCookie object is returned, allowing you to view the expiration date as well as the value, which you access via the Value property:

 
 private void Page_Load(object sender, System.EventArgs e) {     if( Request.Cookies["Name"] != null )     {         lblHello.Text = "Hello " + Request.Cookies["Name"].Value + "! Welcome back!";         tbName.Visible = false;         btnSubmit.Visible = false;     }     else     {         lblHello.Text = "Please enter your name: ";     } } 

Comments

Cookies are yet another way to persist data, but rather than stored in memory on the server like the Application and Session objects, the data is stored on the local file system of a connecting user. You shouldn't rely on cookies for vast amounts of data storage. Because cookies are viewed by some users as an invasion of privacy, they might have turned off the ability for the browser to accept cookies. In other words, if your page will not function without the use of data contained within a cookie, then you should find a different method of data storage.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net