Thursday, 31 October 2013

ASP.NET Cookies

ASP.NET Cookies

Cookies provide the ability to store small amounts of data on a clients machine. It is often used to store
user preferences, session variables, or identity. When the user visits your Web site another time, the
application can retrieve the information it stored earlier. The browser is responsible for managing
cookies on a user system. Cookies can be created, accessed, and modified directly by script running on
the client and pass between the client and server during requests.
Writing Cookies
vb.net
Response.Cookies("userName").Value = "John" Response.Cookies("userName").Expires =
DateTime.Now.AddDays(1)
C#
Response.Cookies["userName"].Value = "John"; Response.Cookies["userName"].Expires =
DateTime.Now.AddDays(1);
Reading Cookies
vb.net
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value) End If
C#
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
Cookies can be either temporary or persistent. Temporary cookies are stored in the clients browser.
These cookies are saved only while your web browser is running. Persistent cookies, on the other hand,
are stored on the hard disk of the client computer as a text file. They stay on your hard disk and can be
accessed by web servers until they are deleted or have expired. These cookies can be retrieved by the
Web application when the client establishes another session with it.
Cookies are limited to 4096 bytes in size and are only capable of storing strings. Browsers also impose
limitations on how many cookies your site can store on the users computer. Most browsers allow only
20 cookies per site; if you try to store more, the oldest cookies are discarded.

No comments:

Post a Comment