Simple .NET Cookie Management


Hello all

Today I will give a short description about using Cookie with .NET , Cookie is one of the most impotent thing to maintain scalability of server as well as manipulation user’s information easier. Generally a Cookie enabled browser can store about 20 cookies for a single domain , so what’s happen ;when you try to keep more cookie in a browser for a particular domain it discard the oldest cookie. If you don’t set the expiration of a Cooke it will remain in memory till the browser session , when you close browser then the cookie is also expire , but when the expiration is set the the cookie is saved in hard drive.

We can manipulate the cookie in two ways as bellow.

// First Example
Response.Cookies["index"].Value = "test value first";
Response.Cookies["index"].Expires = DateTime.Now.AddDays(1);
// Second example
HttpCookie httpCookie = new HttpCookie("NewCookie");
httpCookie.Value = "tast value second";
httpCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(httpCookie);

To retrieve the Cookies information we have to do as following . But one thing we all should have to remember that each and ever time when we try to retrieve data from cookie we have to check that the cookie is no “null”. If the cookie is null and we want to retrieve data from that cookie it will through an exception.

// First Example
if (Request.Cookies["index"] != null)
Response.Write(Request.Cookies["index"].Value.ToString());
else
Response.Write("Cookie not set.");

// Second example
if (Request.Cookies["NewCookie"] != null)
Response.Write(Request.Cookies["NewCookie"].Value.ToString());
else
Response.Write("Second Cookie not set.");

That’s all for today .

BYE

,

Leave a Reply