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 manages the cookies on client computers. Cookies are sent to the client using the
There are two ways to write a cookie to a user's computer. You can either directly set cookie properties on the Cookies collection or you can create an instance of the
For more information, see ASP.NET Cookies Overview.
To write a cookie by setting cookie properties on the Cookies collection
-
In the ASP.NET page you want to write a cookie, assign properties to a cookie in the Cookies collection.
The following code example shows a cookie named
UserSettings
with the values of the subkeysFont
andColor
set. It also sets the expiration time to be tomorrow.Visual BasicВ Copy Code Response.Cookies("UserSettings")("Font") = "Arial" Response.Cookies("UserSettings")("Color") = "Blue" Response.Cookies("UserSettings").Expires = DateTime.Now.AddDays(1)
C#В Copy Code Response.Cookies["UserSettings"]["Font"] = "Arial"; Response.Cookies["UserSettings"]["Color"] = "Blue"; Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);
To write a cookie by creating an instance of the HttpCookie object
-
Create an object of type HttpCookie and assign it a name.
-
Assign values to cookie's subkeys and set any cookie properties.
-
Add the cookie to the Cookies collection.
The following code example shows an instance of the HttpCookie object named
myCookie
, which represents a cookie namedUserSettings
.Visual BasicВ Copy Code Dim myCookie As HttpCookie = New HttpCookie("UserSettings") myCookie("Font") = "Arial" myCookie("Color") = "Blue" myCookie.Expires = Now.AddDays(1) Response.Cookies.Add(myCookie)
C#В Copy Code HttpCookie myCookie = new HttpCookie("UserSettings"); myCookie["Font"] = "Arial"; myCookie["Color"] = "Blue"; myCookie.Expires = DateTime.Now.AddDays(1d); Response.Cookies.Add(myCookie);
Robust Programming
By default, cookies are shared by all pages that are in the same domain, but you can limit cookies to specific subfolders in a Web site by setting their
If you do not specify an expiration limit for the cookie, the cookie is not persisted to the client computer and it expires when the user session expires.
Cookies can store values only of type
Security
Do not store sensitive information, such as a user name or a password, in a cookie. For more cookie security information see ASP.NET Cookies Overview.