Client Side State Management : Cookies

Client Side State Management : Cookies

When you go to a website and the website leaves a txt file/files on your computer that contains information for the website to use the next time you come to the site called Cookies.Cookies are used to identify a user, to store state information, user selection options and other details of the user and etc.

C# code to create a cookie.

//Create a cookie
HttpCookie trialCookie = new HttpCookie(“ABC”);
trialCookie.Value = txtLoginName.Text;

//To set expiration time of cookie to 20 minutes from now.
trialCookie.Expires = DateTime.Now + new TimeSpan(0,0,20,0);

//Add the cookie to users computer
Response.Cookies.Add(trialCookie);

The cookie can also save multiple values:
Response.Cookies[“cookie1”][“key1”].Value = “value1”;

To access the cookies

if (Request.Cookies[“ABC”] == null)
{
//The cookie is not available go on without it.
}
else
{
//Cookie is still there let’s read it.
string oldValue = Request.Cookies[“ABC”].Value;
}

Cookies Drawbacks

  • The user can disable cookies in browser.
  • Most browsers support cookies of up to 4096( 4k) bytes. This limitation makes the cookies a way to store only small amount of data.Some new browsers supports up to 8k data
  • Browsers have a limit on the amount of cookies a web site can save in the client.Most browsers allow only 20 cookies per site.
  • We can not leave critical information in cookies, as they are places on client computer and information can be easily found.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s