Search This Blog

Thursday, May 14, 2009

Cookies in Asp.Net

Cookies

A Cookie is a small text file that the browser creates and stores on the hard drive of client machine. Cookie just one or more pieces of information stored as text strings. A Web server sends client a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced. The most common use of a cookie is to store information about the User and preferences the user makes.

I order to create a cookie you have 2 variable must be defined as they are the cookie name and the duration of the cookie before it expired

How To Create Cookies In Asp.net & Get Cookie Value

protected void Page_Load(object sender, System.EventArgs e)
{
HttpCookie myCookie= new HttpCookie("Address");
myCookie["Country"] = "India";
myCookie["City"] = "Kolkata";
myCookie["Name"] = "Subhamay";
myCookie.Expires = DateTime.Now.AddDays(2);
Response.Cookies.Add(myCookie);
Label1.Text = "I have Created My own Cookie successfully!";

HttpCookie cookie = Request.Cookies["Address"];

if (cookie != null)
{
string country = cookie["Country"];
string city = cookie["City"];
string name = cookie["Name"];

}
}


Cookies With Key Value : A Different Approach

Creating New Cookie
HttpCookie myCookie = new HttpCookie("Cars");

add some key value to the cookie

myCookie.Values.Add("muffin", "chocolate");
myCookie.Values.Add("babka", "cinnamon");


add the cookie to cookie collection
Response.Cookies.Add(myCookie);
//how to get the keys and values stored in a cookie:

Response.Write(myCookie.Value.ToString());
The output to using this with the previous created cookie is this: "muffin=chocolate&babka=cinnamon".

Set Life Time Of A cookie

myCookie.Expires = DateTime.Now.AddHours(12); Or

myCookie.Expires = DateTime.Now.AddDays(7);


If Cookie Expires property is not set then cookie will be created for the current

browser instance
Setting the cookie's path

set a path for a cookie so that it will be available only for that path in your website

myCookie.Path = "/mydomain";
Setting the domain for a cookie

myCookie.Domain= "mydomain.mysite.com";

How To Destroy A Cookie

there is no method called delete or destroy ..So you can use

myCookie.Expires = DateTime.Now.AddDays(-1);
For Removing a subkey:

myCookie.Values.Remove("babka");



No comments: