Cookies in Asp.Net

http-cookies-in-asp-net
We many time use the Cookies, Session, and Application objects. But we are not familiar how they works and how to utilize them efficiently lets see about the cookies.

What are Cookies in Asp.Net or Web Application?

  • Cookies are the small files that are created on the client’s system (End User) or client browser memory (if purly temporary).
  •  Using Cookies we can store small pieces of information or data in a client system and that can be used when needed. The most interesting thing about cookie is that it works transparently with the user.
  • It can be easily used anywhere in our web application.
  • Cookies stores information in plain text format.
  • If a web application uses cookies, the server sends cookies and the client browser will store it in the local computer. The browser then returns the cookie to the server the next time the page is requested.
  • The most common examples of using a cookie are to store user information, user preferences, password remember option, etc.
  • Cookies have many advantages and disadvantages.

How Cookies Works in Asp.Net or Web Application?

When end user open the page or login on some website or make a request for some information to server, the server send Cookies to the client or lest say end user’s computer. This cookie send by server can be used for subsequent Request. like fetching the data, or managing the capabilities.
lest have a quick example,
If Facebook.com stores the username as cookie, so when client reach to the Facebook server for 1st time than the server will ask for logon, the end user will enter the user name and password for later purpose the server also send the cookies which stores the username for future use.

cookies-creation

Now for all subsequent requests like fetch wall, friends, photos etc, from the same client, it uses the session-ID from the cookies, just like in the picture below:

request-after-cookies-creation The browser and web server are responsible for exchanging cookies information. For different sites, the browser keeps cookies differently. If a page needs information from the cookies, when that URL is hit, first it searches the local system for cookies information, then it is moved to the server with that information.

Advantages of Cookies

  • It’s very simple to use and implement.
  • Browser takes care of sending the data.
  • For multiple sites with cookies, the browser automatically arranges them.

Disadvantages of Cookies

  • It stores data in simple text format, so it’s not secure at all.
  • There is a size limit for cookies data (4096 bytes / 4KB).
  • The maximum number of cookies allowed is also limited. Most browsers provide limits the number of cookies to 20. If new cookies come, the old ones are discarded. Some browsers support up to 300.
  • We need to configure the browser. Cookies will not work on a high security configuration of the browser.

How to create Cookies in Asp.Net ?

For working with cookies, we need to use the namespace System.web.
Imports System.web
Have a look at the code and see how we create cookies and add it with a web response.

// Creating a Cookie Object
HttpCookie userinfo = new HttpCookie (“userdetail”)
// Setting a value inside it
userinfo[“username”] =“mishra”
userinfo[“userbgcolor”] =“red”
// adding Cookies to Web response
Response.Cookies.Add (userinfo);

The cookies which have been created will persist or last until the browser is closed. We can persist cookies beyond that. But how? I have explained this below.

How to Get/Read data from Cookies in Asp.Net?

Now it is time to retrieve data from the cookies. Before reading the cookies, first we need to check whether a cookie do exist or not. It is always a good practice to check a cookie before reading it, because the browser might have disabled cookies so this could be end with a fatal error.

// Retrive cookies by Cookie Name
HttpCookie _getuserinfo = Request.Cookies[“userdetail”];
String _username;

//Validate the Cookies
if(_getuserinfo != NULL)
{
 _username = _getuserinfo["username"];
}

Here the username will be assign to our object that is _username.

What are persistent and non-persistent Cookies?

Persistent cookies

These can be called permanent cookies, which are stored in the client’s hard-drive until they expire. Persistent cookies should be set with an expiration dates. Sometimes that lasts until the user manually deletes the cookies. Persistent cookies are used to collect identification information about a user from the system.

How to create persistent Cookies in Asp.Net?

I have already given an example of non-persistent cookies. For persistent cookies, we need to add an expiration time. In the given code, I have specified 1 days means the cookie will expire in 24 hours from the creation time.

//Creting a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

//Setting values inside it
_userInfoCookies["UserName"] = "mishra";
_userInfoCookies["UserColor"] = "Blue";
_userInfoCookies["Expire"] = "3 Days";

//Adding Expire Time of cookies
_userInfoCookies.Expires = DateTime.Now.AddDays(1);

//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

The most interesting thing is where they are stored in the hard drive.

How to remove persistent Cookies before its expiration time ?

This is really a funny task to do because we are not aware about how many cookies are stored in our browser or say computer. If you want to remove persistent cookies before the expiration date, Then the only way is to replace them with cookies with a past expiration date. this will force them to remove instantly.

HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
//Adding Expire Time of cookies before existing cookies time
_userInfoCookies.Expires = DateTime.Now.AddDays(-1);
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

Non-persistent Cookies

These can be called temporary Cookies. If there is no expiration time defined, then the cookie is stored in the browser memory. There is no difference between modifying a persistent and non-persistent cookie. The only difference between them is persistent cookies should have an expatriation time defined.

Where are Cookies stored in the local hard drive?

This is one of the interesting things to know to find out cookies in your local drive. First of all, from Windows Explorer Folder Options, select show hidden files and folders. so that we can see the hidden folder which are containing the data.
show-hidden-folders

Now browse into Documents & Settings of the current user and open the cookies folder. Take a look at this picture.

reading-cookie-info-in-local-pc

How to control Cookies scope?

We can control the scope of cookies using the following ways,

  • Limiting Cookies to Path
  • Limiting Cookies Domain

What is Cookie Munging?

By default, ASP.NET uses cookies to stores session IDs, but as I have already mentioned, some browser do not support cookies. To overcome this problem, ASP.NET uses “Cookie Munging” to manage session variables without cookies.
[Though this is related with Session, I am just giving a basic overview. I will explain this in detail in my next article which will be on Session.]

Why are we using Cookie Munging in ASP.NET?

There are some specific reasons to use cookie munging in ASP.NET:

  • Some browsers do not support cookies.
  • Sometimes users disable cookies in the browser.

How Cookie Munging works?

When the user requests for a page to the server, the server encodes the session ID and add it with every HREF link in the page. When user click on a link, ASP.NET decodes that session ID and passes it to the page that the user has requested. Now the requesting page can retrieve any session variable. This all happens automatically if ASP.NET detects that the user’s browser does not support cookies.

how-cookies-are-managed

How to implement Cookie Munging?

For this, we have to make session state cookie-less.

<sessionState cookieless= "true />;

How to configure Cookies in the browser?

We can now take a look at how we can configure the browser for enabling/disabling cookies. I have already discussed about settings in the IE browser. Click on Tools » Internet Options » go to Privacy tab. There you will be able to see a scroll bar with the following options:

  • Accept All Cookies
  • Low
  • Medium
  • Medium High
  • Block All Cookies

The first option will accept all cookies and the last option will block all cookies. You can get the details of those settings while scrolling the bar.

About Pashupatinath Mishra

Pashupatinath Mishra is Software Developer and our Fulltime blogger. He is having good knowledge on the Different Technologies and also having shareable knowledge on Nutrition, Science Topics, Travel and History.

Website

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.