State Management Part 3 - Cookies

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

Following the session part we now come face to face with cookies. Cookies are small-size files stored in the client's disk, that usually contain personal non-sensitive data. They are used extensivelly by web applications and are supported by most browsers.


What is a cookie?

When you log in a website, close your browser and, a few days later, return to the website, you will most likely be automatically logged in. That's because that website has created something in your disk which stores some piece information, for example our user ID. Next time we visit that website, server will check this info in our cookies, and notice that we have a user ID, which will use to log us in.
We can use cookies for whatever we wish to store, based on the client. We can tell if this is the first time a visitor drops by our page, or if he has already voted in our poll. We can even store products he has already inserted in his e-shop cart so that next time he visits, his cart is still full.

Cookie attributes

Cookies are small text files stored in the user's hard disk. The path used, depends on the operating system.
A cookie will stay tuned to the browser it was created for, until it is expired. As you can guess, logging through chrome will create a cookie, that firefox (or any other browser) will not be able to read. 
Cookies can only be read by the web application for which they were created. 
Cookies can be modified by the user. Therefore it is not a good idea to use cookies to store sensitive data. If a user ID is stored in a cookie, user can modify it, and log in as a different person. An eavesdropper could also steal away your id and insert it into his own cookie. If however you still wish to store sensitive info, then make sure it is encrypted and use secure connections.
Information in cookies is stored in string form, as it is kept in a text file. So, keep in mind it would be hard to save object values that way. Browsers, tend to have limitations concerning the number of cookies per domain allowed, and the size of the cookies, so you have to be carefull not to use cookies careless.
Most browsers support cookies. They also offer the ability to disable them. Even though cookies are harmless, there are people who look upon them as means of violating web privacy and have them disabled. In that case websites using cookies will become malfunctional.

Cookies in ASP.NET

To store a cookie to the client you have to follow these simple steps.
//Create an object HttpCookie (located within the System.Web library) , with a given name.
HttpCookie cookie = new HttpCookie("LanguageCookie");
// Set a value in it, assigned to a specified key.
cookie["Language"] = "English";
// Set the expiration date. If it is not set, then the cookie will be lost when we close the browser or redirect to another page. 
//This cookie' s expirations date is set to one year from now.
cookie.Expires = DateTime.Now.AddYears(1);
// Add it to the web response.
When a request is made, it contains all cookies available for this domain. To load data stored in a cookie, we have to select that cookie first.
// Load cookie from Request.
HttpCookie cookie = Request.Cookies["LanguageCookie"];
string language;
//Always check if cookie exists before trying to get the value.
 if (cookie != null)
    language = cookie["Language"];
That way we can easily set and get values using cookies.
We should always check whether a cookie exists before accessing it. If the user has cookies disabled or our cookie has expired we would get a NullReferenceException.
To edit a cookie simply replace the cookie's old value with a new one like that.
cookie["Language"] = "Greek";
To delete a cookie set the Expires attribute less than DateTime.Now. For example
cookie.Expires = DateTime.Now.AddYears(-1);
There is no easy way to know if a browser has cookies enabled. To do this you will have to try and store a cookie to the client. If the next request contains it, then cookies are enabled.
To check if the browser supports cookies we can examine the Request.Browser.Cookies attribute.
Keep in mind that session needs to use a cookie called ASP.NET_SessionId. As a result, deactivating cookies in user's browser will deactivate session as well.

An example of cookies.

Let's try an example of how to use cookies in ASP.NET using C#. 
Remember the example we created last time to show how session works? We created a few pages of a flight company site, used so the client can choose the country and city he would like to travel for free. It seems the company recently heard that most web sites use cookies, so they want to try this out as well. They know that if we use cookies, a user can turn off his system and if he returns, a month later, the application will still show the selections he has made last time. At no extra cost for the database.
So we modify our aspx webpages using cookies this time.
    Select the country you wish to visit:
    <br />
    <asp:DropDownList runat="server" ID="CountriesListID"  AutoPostBack="true"  OnSelectedIndexChanged="CountrySelected">
    <asp:ListItem Text="" Value="0" />
    <asp:ListItem Text="Italy" Value="1" />
    <asp:ListItem Text="France" Value="2" />
    <asp:ListItem Text="Greece" Value="3" />
    <asp:ListItem Text="United Kingdom" Value="4" />
   protected void CountrySelected(object sender, EventArgs e)
        // Create cookie.
        HttpCookie cookie = new HttpCookie("LocationCookie");
        // Set a value in it.
        cookie["Country"] = CountriesListID.SelectedItem.Text;
        // Set the expiration date to one year from now.
        cookie.Expires = DateTime.Now.AddYears(1);
        // Add it to the current web response.
So, now we have stored the country value in the cookie. We are now redirected to the CitiesCookies.aspx page.
    Select the city you wish to visit:
    <br />
    <asp:DropDownList runat="server" ID="CitiesListID" AutoPostBack="true" OnSelectedIndexChanged="CitySelected">
        <asp:ListItem Text="" Value=""/>
containing the following cs code. 
 protected void Page_Load(object sender, EventArgs e)
        //Checking for postback is often used so that DropDownList controls are filled with ListItems only the first time they are requested 
        if (!IsPostBack)
            HttpCookie cookie = Request.Cookies["LocationCookie"];
            if (cookie != null)
                // Page gets value that was inserted to Cookie in CountriesCookies.aspx
                // Shows cities available to selected country
                string countryValue = cookie["Country"];
               if(countryValue == "Italy")
                    CitiesListID.Items.Add(new ListItem("Rome", "1_1"));
                    CitiesListID.Items.Add(new ListItem("Florence", "1_2"));
                else if(countryValue == "France")
                    CitiesListID.Items.Add(new ListItem("Paris", "2_1"));
                    CitiesListID.Items.Add(new ListItem("Cannes", "2_2"));
                else if (countryValue == "Greece")
                    CitiesListID.Items.Add(new ListItem("Athens", "3_1"));
                    CitiesListID.Items.Add(new ListItem("Mykonos", "3_2"));
                else if (countryValue == "United Kingdom")
                    CitiesListID.Items.Add(new ListItem("London", "4_1"));
                    CitiesListID.Items.Add(new ListItem("Birmingham", "4_2"));
     protected void CitySelected(object sender, EventArgs e)
        //Get the cookie
        HttpCookie cookie = Request.Cookies["LocationCookie"];
        if (cookie != null)
            // Set a new value in it.
            cookie["City"] = CitiesListID.SelectedItem.Text;
            // Add it to the current web response.
The page will load only the cities located to the selected country. Ater selecting the city, its value will be stored in the same cookie and we will be redirected to the final page CheckOut.aspx.
CheckOut.aspx contains the following piece of code.
    Congratulations, next week you are flying to 
    <asp:Literal runat="server" ID="CheckOutLitID" />
protected void Page_Load(object sender, EventArgs e)
        string location = "";
        //Get Cookie values
        HttpCookie cookie = Request.Cookies["LocationCookie"];
        if (cookie != null)
            location += cookie["City"].ToString();
            location += " , " + cookie["Country"].ToString();
        CheckOutLitID.Text = location;


Cookies is quite a handy way to store info. It takes up only a small space of the client's disk, and does not create traffic as its content is not large enough to do so. Using cookies is an insecure way to store info, so it should not be used to store sensitive data. 

Back to BlogPreviousNext


    Leave a comment