Wednesday, October 22, 2008

Using and Understanding Cookies in ASP.NET

Using and Understanding Cookies in ASP.NET
This article explain about Cookies, and understanding more about using cookies in your web applications.

Introduction

This article will explain about cookies and how to use Cookies in your ASP.NET applications. As we all know that cookies is very popular and being used by almost all websites in the world to track user information such as logon details, length of visit, number of visits and etc.

A cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings. A Web server sends you a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced.

Most of our browsers by default are set to accept cookies from website. You can actually override this in your browser settings if you like to prevent storing cookies while browsing. But most of the website these days will requires cookies to be enabled on your site before you can use all their site features.

Cookies Limitation

Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store.

Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.

A cookie limitation that you might encounter is that users can set their browser to refuse cookies. If you define a P3P privacy policy and place it in the root of your Web site, more browsers will accept cookies from your site. However, you might have to avoid cookies altogether and use a different mechanism to store user-specific information.

Although cookies can be very useful in your application, the application should not depend on being able to store cookies. Do not use cookies to support critical features. If your application must rely on cookies, you can test to see whether the browser will accept cookies. There are code snippets you can do to check if your client browser has cookies enabled or not. I will explain later about this throughout the article.

Writing Cookies in ASP.NET

Writing Cookies in ASP.NET is quite simple and easy. The System.Web namespace offers a class called HttpCookie to write cookies on your browser.

Please note that Cookies depends on the expiration date for their lifetime. You need to set the cookies expiration date to be greater than current time or else you will not be able to read the cookies back.

Also, You can write a cookies without the need to set the expiration date. And if you do so, your cookies will be stored in browser memory and the cookies life time is depends on your browser.If you close your browser, then all your cookies will be removed.

The following code below demonstrates the creation of cookies.

HttpCookie oCookie2 = new HttpCookie("UserName");
oCookie2.Value = "MyUserName";
oCookie2.Expires = DateTime.Now.AddMinutes(120);
HttpContext.Current.Response.Cookies.Add(oCookie2);

Or there is another shorter way of adding cookies

Response.Cookies["UserName"].Value = "MyUserName";
Response.Cookies["UserName"].Expires = DateTime.Now.AddMinutes(120);


Both of the example above achieve the same thing. The first one do that by creating new instance of the HttpCookie object and then later on add the cookie inside the Response.Cookies object,while the second one directly called the Response.Cookies object and set the properties directly.

Once you have write run the code above, you can see a cookies actually has been written on your machine. IE and Mozilla stored the cookies in different location. And both browsers cannot read cookies created by different browsers.

IE will normally stored your cookies inside "C:\Documents and Settings\Default User\Cookies "
And mozilla will normally stored cookies inside your mozilla profile directory

Storing Cookies with More than One Value
You can store one value in a cookies such as username and last visit. There is a way for you to store more than one value under one single cookie.

The advantage of storing multiple key value under one single cookie will help you to overcome the limit of the cookie. Remember that there is a limit of 20 cookies allowed per one website and also Cookies sizes are limited to 4096 bytes. Each single new cookies that you create will impose an overhead of 50 bytes. So rather than have to create each cookies for every single value you want to store, you can actually achieve that by combining all the values into one single cookies. The way you retrieve the multi value cookies is by using the name value pair.

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

Reading Cookies in ASP.NET

After you have read the section above, you can see that writing cookies is quite simple and easy. Once you have write the cookies, there must be a way for you to retrieve it back on the server. Writing Cookies will use HttpResponse object, while reading cookies will use HttpRequest object.

When a browser makes a request to the server, it sends the cookies for that server along with the request. In your ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class. The structure of the HttpRequest object is essentially the same as that of the HttpResponse object, so you can read cookies out of the HttpRequest object much the same way you wrote cookies into the HttpResponse object. The following code example shows two ways to get the value of a cookie named username and display its value in a Label control

if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}

Before trying to get the value of a cookie, you should make sure that the cookie exists; if the cookie does not exist, you will get a NullReferenceException exception. Notice also that the HtmlEncode method was called to encode the contents of a cookie before displaying it in the page. This makes certain that a malicious user has not added executable script into the cookie.

Because different browsers store cookies differently, different browsers on the same computer won't necessarily be able to read each other's cookies. For example, if you use Internet Explorer to test a page one time, but then later use a different browser to test again, the second browser won't find the cookies saved by Internet Explorer.

Modifying Cookies in ASP.NET

Modifying the cookies in ASP.NET cannot be done directly. Changing the values of cookies would require you to creating a new cookie with new values and then send it to browser to overwrite the old version on the client. The following code shows you how to achieve that.

string UserName = "NewUserName";
if(Request.Cookies["UserName"] != null) {
//Cookies Exists,so we change the cookies value
Response.Cookies["UserName"].Value = UserName;
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);
}

Based on the code above, you can see that modifying the cookies code,is just the same as creating new cookies.

Deleting Cookies in ASP.NET

Deleting a cookie which means physically removing it from the user's hard disk is a bit tricky and basically you cannot do it in server side code. You cannot directly remove a cookie because the cookie is on the user's computer. However, you can have the browser delete the cookie for you. The technique is to create a new cookie with the same name as the cookie to be deleted, but to set the cookie's expiration to a date earlier than today. When the browser checks the cookie's expiration, the browser will discard the now-outdated cookie. The following code example shows one way to delete all the cookies available to the application:

Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);

Determining Whether a Browser Accepts Cookies

Users can set their browser to refuse cookies. No error is raised if a cookie cannot be written. The browser likewise does not send any information to the server about its current cookie settings. You can actually do a simple test Code by writing and reading back the cookies. If you cannot retrieve back the cookies you just set, it means that client has blocked the cookies.
Following code snippet will show you how to achieve that.

Response.Cookies["TestCookies"] = "TestCookies";
Response.Cookies["TestCookies"].Expires = DateTime.Now.AddDays(10);

if(Request.Cookies["TestCookies"] != null) {
Response.Write("Client accept cookies");
}
else {
Response.Write("Client reject cookies");
}

1 comment:

Anonymous said...

This is great! I'm going to read more!!!