Cookies provide a means in Web applications to store user-specific information, such as history or user preferences. A cookie is a small bit of text that accompanies requests and responses as they go between the Web server and client. The cookie contains information that the Web application can read whenever the user visits the site.
The browser is responsible for managing cookies on a user system. Cookies are sent to the server with a page request and are accessible as part of the
Procedure
To read a cookie
-
Read a string from the Cookies collection using the cookie's name as the key.
The following example reads a cookie named
UserSettings
and then reads the value of the subkey namedFont
.Visual BasicВ Copy Code If (Request.Cookies("UserSettings") IsNot Nothing) Then Dim userSettings As String If (Request.Cookies("UserSettings")("Font") IsNot Nothing) Then userSettings = Request.Cookies("UserSettings")("Font") End If End If
C#В Copy Code if (Request.Cookies["UserSettings"] != null) { string userSettings; if (Request.Cookies["UserSettings"]["Font"] != null) { userSettings = Request.Cookies["UserSettings"]["Font"]; } }
Compiling the Code
This example requires:
-
An ASP.NET Web page.
-
A cookie written previously named
UserSettings
, as illustrated in the topic
Robust Programming
For security reasons, you can read only cookies that are set by pages that are part of the same domain. If the cookie's
When reading specific cookie values, test that the cookie exists and that it has a value, otherwise an exception will occur.
All values in a cookie are stored as type
Security
The browser can send the data back only to the server that originally created the cookie. However, malicious users can access cookies and read their contents. Do not store sensitive information in a cookie, such as a user name or password. Instead, store a token that you can use to look up the sensitive information on the server. Additionally, cookies can be tampered with, so any data in cookie should be treated with the same measures you use to prevent cross site scripting attacks. See Script Exploits Overview for more information.