This documentation is archived and is not being maintained.

Code: Reading a Cookie (Visual C#)

Visual Studio .NET 2003

The following example uses the HttpCookie class and its properties to read a cookie with a specific name.

Example

HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");

Compiling the Code

Start a new ASP.NET Web application and paste the code into the Page_Load method.

Robust Programming

Replace the name "MyTestCookie" with the name of the cookie to be read.

Values returned from a cookie are always of type string.

Security

The browser can only send the data back to the server that originally created the cookie. However, malicious users can access cookies and read their contents.

See Also

Code: Writing a Cookie (Visual C#) | HttpCookie Class | Web Applications Example Topics

Show: