You can store small pieces of user-specific information in the user's Cookies collection
on the user's local machine, assuming the local browser supports cookies and the user has
not disabled this feature.You can use cookies to hold data for as long as the current
browser window is open, or you can give them an expiration date some time in the
future.The first variety is called an in-memory cookie, because they are never written to
the user's hard drive.The second variety is referred to as a persistent cookie, because
these cookies persist across browser and even machine restarts.
There are several ways to work with cookies in ASP.NET.The simplest uses syntax
very similar to that used for the Application and Session collections:
'write a cookie
Response.Cookies("UserName").Value = UserNameTextBox.Text
'read a cookie
UserNameLabel.Text = Request.Cookies("UserName").Value
In addition, you can give the cookies an expiration date, which will cause them to be
persisted to the user's hard drive.To delete these (and other) cookies, simply set their
expire date to any past date, as shown:
'persist a cookie
Response.Cookies("UserName").Expires =
➥
System.DateTime.Now.AddDays(1) ' persist for 1 day
'delete a cookie
Response.Cookies("UserName").Expires = System.DateTime.Now.AddDays(-1)
Comments
Cookies can be a great place to store small pieces of data that are needed from page to
page.They do not have the overhead of sessions, and they can span multiple user visits
over large time periods.They can also span applications within the same domain (for
example, yahoo.com). Not all users will accept cookies, however. It's best to test for this
by writing a test cookie and attempting to read it back on a subsequent request. Cookies
can store only small amounts of text data, with an upper limit of less than 4KB, which
includes the data and the keys used to extract the data (for example, UserName in the
previous example).
No comments:
Post a Comment