Hour 3: Understanding 5 ASP.NET State management techniques in 5 hours

Cookies: A Cookie is one of several ways to store data about web site visitors when the web server and the browser are not connected. They are small files
that are created on the client's hard drive (or, if they're temporary, in the web browser's memory).

Benefits of a Cookie:

  1. They work transparently without the user being aware that information needs to be stored.
  2. It is used by any page in the application
  3. Retain user information between visits, which allows for truly long-term storage
  4. Cookies do not require any server resources since they are stored on the client.
  5. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).

  1. Users can delete cookies.
  2. User's browser can refuse cookies, so your code has to anticipate that possibility.
  3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.

Scenario #1: How to create and implement a cookie.

HttpCookie myCookie = new HttpCookie("Visitordetail");
        //We created the cookie but there are no keys with values in it, so for now it's useless. So let's add some:
        myCookie["Country"] = "India";
        myCookie["VisitorName"] = "Vishal Nayan";
        myCookie["Language"] = "English";
        //We also need to add the cookie to the cookie collection   
        //this cookie persist for 7 days
        myCookie.Expires = DateTime.Now.AddDays(7);
        //Check to see whether a cookie was found with this name.
        HttpCookie cookie = Request.Cookies["Visitordetail"];

        // Check to see whether a cookie was found with this name
        if (cookie != null)
            string sCountry = cookie["Country"];

        //How to remove a cookie

        //OR replacing it with a cookie that has an expiration date that
        //has already passed
        cookie.Expires = DateTime.Now.AddDays(-1);

Scenario #2: Generate Cookie for Remember me.

Below code below will create a cookie at client side for login name and password (for the purpose of security, passwords should not be stored). It will do the following.

  1. Check if remember me check box is checked or not

  2. Create cookie object

  3. Remove old and add new cookie with appropriate values.

  4. Set the expire time of cookie.

//suppose on login page we a checkbox to remember the user
        CheckBox cbk = new CheckBox();
        TextBox txtUsername = new TextBox();
        txtUsername.Text = "Vishal Nayan";
        cbk.Checked = true;

        if (cbk.Checked)
            HttpCookie loginCookie = new HttpCookie("logindetail");
            if (loginCookie != null)

                myCookie.Values.Add("UserInfo", txtUsername.Text);
                DateTime cookieExpiry = DateTime.Now.AddDays(5);
                Response.Cookies["logindetail"].Expires = cookieExpiry;


Scenario #3: How to determine whether a web browser accepts cookies

There are two possible cases when your client will not accept cookies:

  1. Web browser does not support cookies

  2. Web browser supports cookies, but the user has disabled that option through a browser's privacy settings.

//How to check  whether visitor's browser have support for cookie
        if (Request.Browser.Cookies)
            // Cookies supported
// Web browser not supports cookies

Note: Request.Browser.Cookies will still return true but your cookies will not be saved. The only way to check the client's privacy settings is to try to save a cookie on the first page, and then redirect to a second page that will try to read that cookie. You can eventually use the same page to save and read a cookie when performiing a test, but you must use Response.Redirect method after saving and before reading cookies.

Scenario #4: How cookies are saved as per domain details

Respective application can read only cookies related to your web domain. You can't read cookies related to other web sites. Web browser stores cookies from different sites separately.

Scenario #5: How to save user login detail at time of login button click

//Another example whcih check whether cookie exists and then takes username and passwords and store
        if ((Request.Cookies["PBLOGIN"] == null))
            //Create a cookie with expiry of 30 days
            Response.Cookies["PBLOGIN"].Expires = DateTime.Now.AddDays(30);
            //Write username to the cookie
            Response.Cookies["PBLOGIN"].Values["UNAME"] = "Vishal Nayan";
            //Write password to the cookie
            Response.Cookies["PBLOGIN"].Values["UPASS"] = "123";
        //If the cookie already exist then wirte the user name and password on the cookie
            Response.Cookies["PBLOGIN"].Values["UNAME"] = "Vishal Nayan";
            Response.Cookies["PBLOGIN"].Values["UPASS"] = "123";

Scenario #6: Multi-Valued Cookies (Subkeys)

We can also store multiple name-value pairs in a single cookie. The name-value pairs are referred to as "keys" or "subkeys," depending on what you are reading. There are a couple of reasons to use subkeys instead of separate cookies. Obviously, it is tidy to put related or similar information into a single cookie. In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the information.

//Multi value cookies
        Response.Cookies["userInfo"]["userName"] = "mike";
        Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
        Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

        HttpCookie aCookie = new HttpCookie("userInfo");
        aCookie.Values["userName"] = "mike";
        aCookie.Values["lastVisit"] = DateTime.Now.ToString();
        aCookie.Expires = DateTime.Now.AddDays(1);

Scenario #7: How to define the scope of a cookie for a particular domain

By default, cookies are associated with a specific domain.

        Response.Cookies["domain"].Value = DateTime.Now.ToString();
        Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
        Response.Cookies["domain"].Domain = "support.vishalnayan.com";

This is the end of your third hour of reading. Hope you enjoyed it.

Click to continue to the fourth hour of reading