Search This Blog

Friday, September 10, 2010

Cookies in ASP.NET

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser.  For example, if a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, the browser stores it in a folder on the user's hard disk.
Later, if user requests a page from your site again, when the user enters the URL the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site.

Also, Cookies are associated with a Web site, not with a specific page. They might be used to remeber passwords, or "Remember me on this computer" etc.

Cookie limitations
The size of cookies needs to be small, usually 4096bytes. And the no of cookies per site or per explorer can also be set. So you cannot have many cookies on ur website. Also, some users may set their browsers to refuse cookies.

Create a cookie
They are two simple ways
1) Response.Cookies["MyName"].Value = "Esha";
    Response.Cookies["MyName"].Expires = System.DateTime.Now.AddDays(2);

2) HttpCookie myCookie = new HttpCookie("SunSign");
    myCookie.value = "Capricon";
    myCookie.Expires = System.DateTime.Now.AddDays(2);
    Response.Cookies.Add(myCookie)

To Retrieve Cookies
  TextBox1.Text = Request.Cookies["MyName"].Value.ToString() + " - " + Request.Cookies["SunSign"].Value.ToString();

To have keys in cookies or cookies with multiple values

Response.Cookies["User"]["Name"]  = "Esha";
Response.Cookies["User"]["SunSign"] = "Capricon";
Response.Cookies["User"]["LastVisited"] = System.DateTime.Now;

To retrieve these values
if((Request.Cookies["User"] != null) && (Request.Cookies["User"].HasKeys()))
{
    for(int i = 0; i < Request.Cookies["User"].Values.Count ; i++)
    {
         TextBox1.Text += Request.Cookies["User"].Values[i].ToString();
    }
}

No comments:

Post a Comment