Tuesday, February 28, 2012

Cookie: How to read and write a cookie in Asp.net

Cookies are very popular in Web development, and used to store visitors data. They Provide another way to store information of web page for later use. Mainly it is used to remember users between visits. You can retain the values of web page during the postbacks and can use the same value in any page of your web application. It is a very small text file and stored in the client machine, but is easily traceable. It has so many limitations #1. User can not store data more than 4096 KB #2. User can easily stops/disable cookies by browser We can use cookies in asp.net by using collections.



Sample Code

//How to Add
void Cookies_Add()
{
HttpCookie LanguageCookies = new HttpCookie("LanguageCookies");
LanguageCookies.Value = "English";
LanguageCookies.Expires = DateTime.Now.AddMinutes(20);
Response.Cookies.Add(LanguageCookies);
}

//How to Read
void Cookies_Read()
{
string str = Request.Cookies["LanguageCookies"].Value;
}

//How to delete
void Cookies_Delete()
{
if(Request.Cookies["LanguageCookies"]!=null)
{
// cookies will be expiry immediatly
Response.Cookies["LanguageCookies"].Expires =
DateTime.Now.AddMinutes(-1);
}
}

No comments: