Create and Read Cookies in ASP.NET

Cookies are small pieces of text which are created by websites and stored by the Internet browser in its cache for later use. Typically a cookie would contain information related to a surfer’s session in a particular website, such as the user name, items in a shopping cart, page layout preferences, etc.

When a surfer visits a website, a cookie would be created with his details, and when he returns to the site his details are loaded from the cookie and sent to the website. This can for example, allow the website to identify who the surfer is and load his last session back.

Cookies can be very useful but they are also easily accessible so it’s advisable to never store sensitive data, such as passwords or credit card numbers, in cookies.

In this short article I am going to show you how to create a cookie in ASP.NET, obviously using C#, and then I will also show you how to read your cookie’s value.

First you must create an ASP.NET Web Application, and once that’s done add two buttons and a label to your Default.aspx web form. The first button we will call“Save Cookie” and the second one “Load Cookie”. The label will be used to display the status on-screen.

In the event handler for the “Save Cookie” button we will create a cookie and add astring value to it. The code should look like this:

protected void btnSave_Click(object sender, EventArgs e)
    // Create a cookie object
    HttpCookie cookie = new HttpCookie("TestCookie");

    // Set the cookie's value
    cookie.Value = "Paul Mercieca";

    // Set the cookie's expiration date
    cookie.Expires = DateTime.Now.AddDays(7);

    // Add the cookie to the cookie collection

    // Display the status
    lblStatus.Text = "Cookie has been created.";

The above code is quite simple. We are creating a cookie called “TestCookie” and assigning it my name as a value. Then we are setting an expiry date of 7 days for the cookie. This means that the cookie will remain valid for 7 days from creation. When that period expires the cookie will be deleted by the web browser. Finally we are adding our new cookie to the Response.Cookies collection which is actually an instance of HttpCookieCollection, and we are setting the status label’s text.

Now to read the cookie. To do this we need to access the HttpCookieCollection instance again by calling Request.Cookies as can be seen in the below code:

protected void btnLoad_Click(object sender, EventArgs e)
    // Retrieve the cookie from the cookie collection
    HttpCookie cookie = Request.Cookies["TestCookie"];

    // Verify the cookie exists
    if (cookie != null)
        lblStatus.Text = string.Format("Hello {0}", cookie.Value.ToString());
        lblStatus.Text = "Cookie not found.";

Again, this code is very straight forward. All we are doing here is retrieving the “TestCookie” and verifying it exists. If it exists we are displaying the cookie’s value, which in this case is my name – “David Azzopardi”, and if it does not exist we are displaying “Cookie not found”.

And there you have it – creating and reading cookies with C# in ASP.NET.

  1. No trackbacks yet.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: