A discussion of state management would be incomplete without at least a brief mention of another option for storing application state: client-side cookies. This method doesn’t work with users whose browsers cannot handle cookies (or who have turned off cookies), but it’s the most lightweight method for storing certain types of state data because it requires no resources on the Web server. In cases where users have cookies turned off, the code that sets the cookie will simply be ignored. If your code expects the cookie to be present, however, you might get an error when attempting to access the cookie. For this reason, you should always wrap code that accesses values in a cookie within a Try…Catch block to ensure
that your application can gracefully recover from a missing cookie.
Create a new instance of the HttpCookie class.
HttpCookie MyCookie = New HttpCookie("MyCookieName");
Set the Value property of the cookie to the desired value.
MyCookie.Value = "MyValue";
Add the cookie to the Cookies collection of the Response object (exposed by the Page class).
Response.Cookies.Add(MyCookie);
This sets a cookie called “My Cookie” that lasts until the user closes the browser.
To store user state that will persist across multiple browser sessions, you need to use persistent cookies. In order for a cookie to be persistent, its expiration must occur in the future. To make the cookie created in the previous example persist for two days, add the following line of code, just prior to adding the cookie to the Response.Cookies collection:
MyCookie.Expires = DateTime.Now.AddDays(2);
Here are some things to consider about using persistent cookies.
Cookies have a bad reputation because of their misuse by some Web companies to track the surfing habits of Web users. It’s a good idea to explain to your users exactly how and why you’re using persistent cookies, and describe the benefits of accepting those cookies.
Keep the expiration of persistent cookies within a reasonable amount of time. For most sites, cookie expiration should be measured in hours or days or, at most, months. Setting your cookie expiration to years in the future is likely to result in more users refusing your cookie.
Never store user data in a cookie (for example, credit card numbers or other data that could be at risk if intercepted or otherwise compromised).
Important |
Although it might seem obvious to avoid storing information such as credit card numbers in cookies, it’s equally important to consider the security implications of storing such information on the server side, whether in session state in memory or in a database server. Although there’s no single right answer to how to store sensitive data, here are some guidelines you should follow:
|
Note |
Although following these guidelines won’t guarantee that your Web applications will never be compromised by crackers, they’ll help you limit the damage. |