Understanding ASP.NET State management techniques-Part III

No.of Views1767
Bookmarked0 times
By  Vishal Nayan   On  02 Jun 2011 08:06:59
Tag : ASP.NET , State Management
Cookie is one of several ways to store data about web site visitors during the time when web server and 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).
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com



Cookie is one of several ways to store data about web site visitors during the time when web server and 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 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 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(don't store password as per security reason). It will do following job.

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 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 find does 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 user 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. Only way to check client's privacy settings is to try to save a cookie on the first page, and then redirect to second page that will try to read that cookie. You can eventually use the same page to save and read a cookie when perform a testing, 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 scope of cookie for 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.codegain.com";

Download Samples 

Download source files -11 kb

This is end of your 3rd part of reading Hope you enjoyed it.

Sign Up to vote for this article
About Author
Vishal Nayan
Occupation-Software Engineer
Member Type-Junior
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
Other popularSectionarticles
    It is a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. A session is defined as the period of time that a unique user interacts with a Web application. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state.
    Published Date : 02/Jun/2011
    It store global objects that can be accessed by any client.It supports the same types what session state support which are of type objects, retains information on the server, and uses the same dictionary-based syntax. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
    Published Date : 09/May/2011
    Http protocol is stateless, so we need to maintain state on Client side or Server side. For this time I am going to discuss about the maintaining state on Server Side with one programming practice.
    Published Date : 10/Jan/2011
    Now web application framework, no matter how advanced, can change that HTTP is a stateless protocol. So inherently we should also forget our users, but unfortunately we cannot.ASP.Net Framework provides us features by which we can maintain states of your users.
    Published Date : 26/Jun/2010
    There is Lots of ways and Techniques Are available to Manage you State on Web in Aspnet
    Published Date : 06/May/2010
There is no comments for this articles.
Leave a Reply
Display Name:
(not display in page for the security purphase)
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top