The first method creates an instance of a Cookie for the user "agivenuser", for this example, we want to store the name, second name, and date of creation. Also we need to set the expiration date for the cookie, in this case only three days. This means that after three days without the user entering the system the cookie will be deleted.
protected void btnSetcookie_Click(object sender, EventArgs e)
{
//Create an instance of a cookie.
HttpCookie userCookie = new HttpCookie("agivenuser");
//Store data
userCookie["Name"] = txbxName.Text;
userCookie["SecondName"]= txbxApellidos.Text;
userCookie["Date"]=DateTime.Now.ToShortDateString();
//Set expiration dates.
userCookie.Expires = DateTime.Now.AddDays(3);
//Store the cookie in the user machine.
Response.Cookies.Add(userCookie);
}
And this method is used to read the cookie for the user
protected void btnGetCookieData_Click(object sender, EventArgs e)
{
if (Request.Cookies["USER"] == null)
{
Response.Write("USER has no cookies");
}
else
{
HttpCookie aCookie=Request.Cookies["USER"];
Response.Write("Cookie stored :" + aCookie["Name"] + " " + aCookie["SecondName"]
+ " " + aCookie["Date"] + " Expires :" + aCookie.Expires.ToString() );
}
}
No hay comentarios:
Publicar un comentario