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 HttpRequest object, which exposes a Cookies collection. You can read only cookies that have been created by pages in the current domain or path.
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 named Font.
Visual Basic
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
Code in C#:
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