This article tells about cookies and how to write and read cookies in ASP.NET web application.
In each cookie you can not save more than 4k of information. Remember clients can open cookies and see the content of a cookie so never save a password there. Cookies are usually used to save user preference information.
Cookies are used to store user specific information in form of text strings. When a user visits particular website some user specific information gets stored and this information can be retrieved later when the same website gets visited from same machine and can be sent to server. Cookies are associated with websites instead of individual pages.
In ASP.NET cookies can be created using class HttpCookie in System.Web namespace.
Cookies are added to the Cookies collection of response object, the object which is responsible for keeping information to be rendered to browser. Example for writing and reading cookie
//Create an instance of HttpCookie
Dim mycookie as new HttpCookie("userid")
//Set parameters like value and expires
mycookie.Value = "1"
mycookie.Expires = DateTime.Now.AddMonths(1)
//Add to the Cookies collection of response object
We can do same thing by directly setting values for Response.Cookies collection
Response.Cookies ("userid").value = "1"
Response.Cookies ("userid").Expires = DateTime.Now.AddMonths(1)
The above code creates cookie and store it in user's drive for one month. The following code is used to retrieve a cookie later.
Request object is used to send cookies information along with the request for page to server.
If Not Requet.Cookies("userid") Is Nothing Then
Dim a As String
a= Not Requet.Cookies("userid")
Here first we are checking whether cookie exists or not because it can be deleted by user. Cookies won't work if user has disabled cookies in browser settings.
To check if the cookie is enabled or disabled on the client side we can use the following script on the first page of the application:
if ( Get_Cookie( 'test' ) )
document.write( 'cookies are currently enabled.' );
this is an example of a set cookie variable, if
you want to use this on the page or on another script
instead of writing to the page you would just check that value
for true or false and then do what you need to do.
cookie_set = true;
// and these are the parameters for Delete_Cookie:
// name, path, domain
// make sure you use the same parameters in Set and Delete Cookie.
Delete_Cookie('test', '/', '');
// if the Get_Cookie test fails, cookies
//are not enabled for this session.
document.write( 'cookies are not currently enabled.' );
cookie_set = false;
This would check if the cookie is enabled or not on the client browser.