We all know that web applications use the
Hyper Text Transfer Protocol (HTTP) for communication. The HTTP protocol works on a
Request/Response pattern and is stateless in nature. It does not retain states between post backs.
In simple terms, it means that when a
Client requests something from a
Web Server, the web server serves the request of the Client and returns the appropriate response. Afterwards, it cleans up the resources used to serve that request. It doesn't retain any information of the request and all the information associated with the request is lost.
Hence, a new instance of the request is created each time a request is received by the Web Server. This results in stateless nature of web applications and there is no persistent connection between the Client and the Server. To overcome this limitation, ASP.NET provides various State Management techniques to preserve data during round trips. In this article, we'll learn about these State Management techniques.
Before I start discussing the State Management techniques, I'm going to show you a simple demo that helps you to understand the meaning of the stateless nature of web applications. In this demo, I'm using two Text Boxes (one from the simple
HTML Controls and another one from the
ASP.NET Server Controls) and a Button. I'm putting some values in these Text Boxes and submitting the values to the web server. Let's see what happens to these values thereafter.
I'm using the newly introduced free
Visual Studio Community 2013 for the demo. Please visit this
link if you need any help regarding installation and setup of Visual Studio Community 2013.
Open Visual Studio, create an empty web application and name it “
By default, for an Empty Web Application, Visual Studio gives us only the
web.config file. Add a new Web Form to the project and name it
I'm sure all of you are familiar with
HTML Controls and
Server Controls in ASP.NET. Read here for
<a href="http://msdn.microsoft.com/en-us/library/620b4fzf%28v=vs.71%29.aspx" target="_blank">more information</a>. In
Demo.aspx, add two Text Boxes, one from the simple HTML Controls and another from Server Controls and also add a Button Control. Now build the project and run the application.
We are shown a demo page with two empty text boxes and a submit button. Let's put some values into these boxes and click on the Submit button.
After we submit the values, the page is posted back to the web server and the results are as in the following:
What happened here is the value of the normal HTML TextBox is lost during the round trip to the server whereas the value of Server Control TextBox is preserved. The HTML TextBox shows the stateless nature of basic HTML Controls whereas the Server Control TextBox shows the advantages of Server Controls provided by ASP.NET to deal with the stateless nature of HTML.
Now, why is the value of a Server Control retained but not the HTML control? This seemed like a mystery to me and I love solving mysteries (not as much as Nicolas Cage though). So, let's determine what exactly happened there.
Why ASP.NET Controls retain their State?
There is an interesting result shown in the preceding example since the values we pass to Server Controls are retained within round trips but the values in HTML Controls are destroyed as soon as it reaches the server. If we dig deep into what really happened, the technical explanation is the implicit use of one of the State Management techniques in Server Controls that help to retain states and that technique is
View State. To be precise, it's the
IPostBackDataHandler interface that the Server Controls implement to preserve the states during round trips and makes them more interesting and important for us. But, View State is not the only technique provided by ASP.NET for State Management. There are various other techniques as well; in fact the entire State Management is divided into two broad categories. I'm not going to discuss all the State Management techniques in this article, only the frequently used ones.
Client-side State Management
The Client-Side State Management technique is used to store data using client-side options where no server resource is used. This technique stores data on the client's browser instead of using the server resources. The major benefit with this technique is better scalability. However, as the data is stored on the client's end, it is less secure and cannot be used to store any kind of sensitive data. ASP.NET provides the following options to implement client-side State Management:
- View State
- Query String
- Control State
- Hidden Fields
Server-side State Management
Server-Side State Management offers high security over the client side for storing data. The data is saved on the server and therefore isn't delivered to the client. However, this technique uses more server resources and can be used wisely. ASP.NET provides the following options to implement server-side State Management:
- Session State
- Application State
State Management Techniques
To better understand these techniques, let's consider a scenario of an imaginary website for developers,
"Developer's Cafe". The website contains two pages,
Dashboard. The Login page contains two text boxes for Username and Password, a Button for submitting the values and three Label controls, one for displaying the welcome message to the user, the other one to display the number of wrong login attempts taken by the user in case of wrong credentials and the last one to display the number of online visitors. The Dashboard page displays the username after a successful login attempt and also provides a logout button to end the current session of the user.
We'll see how the various state management techniques fit into this scenario. The complete source code of the application can be downloaded from my
<a href="https://github.com/iSahilSharma/StateManagementDemo" target="_blank">GitHub account</a>.
Note: Please note that the real world scenario presented in this article is just for educational purposes, so that a reader can understand the techniques. It cannot be implemented in a live project as such. There are several selection criteria to be considered before using State Management techniques as each of them has its own advantages as well as disadvantages.
View State is a page-level state management technique used to store information between multiple requests of the same page. View State is the default mechanism for ASP.NET Server Controls to preserve a page and control property values between round trips.
View State uses the page memory to store information and is implemented using hidden form fields on the same page with the name _VIEWSTATE. The items stored in View State exist for the life of the current page. View State is enabled by default for web controls as well as the entire page. However, we can disable the View State from storing data by changing the EnableViewState property to
- View State is the default mechanism of ASP.NET Server controls to retain states during round trips.
- It is a dictionary type of the State Bag collection class and can be used to store any type of data.
- It is a perfect place to store data that is used for multiple post backs in a single web page.
- The major drawback of View State is that the information is stored only for the current page. Once the user is redirected from the current page to another page or closes the page accidentally, View State is destroyed and cannot transfer to the redirected page.
- The information stored in View State is not encrypted by default and can be easily tampered by anyone. So it cannot be used to store any kind of sensitive data. However we can encrypt the View State using
- The View State cannot be used to store a large amount of data since it causes the page size to increase and causes overhead issues.
Real World Scenario
Login page, suppose we need to count the number of login attempts of a
User in the case of a wrong password. If the User enters a wrong password, it will be redirected to the same
Login page again. The View State mechanism fits perfectly to this situation and we can use it to count the number of wrong attempts a user takes to login into the website. The View State object is a dictionary type that allows us to save and restore any data across multiple requests of the same page. It may be noted that we cannot pass view state data from one page to another.
The following image shows the use of View State in a
Login page. If the user enters the correct credentials, it will be redirected to the next page. However, if the user enters a wrong password, it is again thrown to the same
Login page and his login attempt is increased by one. We are counting the number of wrong attempts a user takes to log into the website.
A cookie is a client-side State Management technique and is commonly used to provide personalization, track usage or to store information about users. A cookie is a small text file that is stored on either the client's machine or in the memory of the client's browser session. The maximum size of a cookie is
4096 bytes or
4KB and generally a total of
300 cookies are allowed on a client machine with
20 cookies per server or a domain.
Cookies are of the two types:
Persistent Cookie: This type of cookie is stored permanently on the hard drive of the client's machine. A persistent cookie has an expiry date and if we do not provide any specific date, it will be treated as Non Persistent or Transient Cookie.
- Non-Persistent/Transient Cookie: This type of cookie is stored in the client's browser memory for a temporary amount of time. It is available only while the browser is running.
- It is very simple and easy to use.
- It takes only a few bytes of memory to create a cookie.
- Cookies can be easily disabled by a user by tweaking the browser settings.
- The only way to remove a cookie is by manually deleting it or replacing it by another cookie that has an expiration date that is already passed.
- Cookies are stored on the client machine, so cannot be used to store any kind of sensitive data.
Real World Scenario
In our example of
Login page, suppose we need to track the visiting history of a
User; that means, we need to check whether the
User is logging into the website for the first time or is a regular visitor. This scenario can be simply done using
Cookies, where we can make use of persistent cookies to identify the user.
The following image shows the implementation of a permanent cookie on the user machine. If the user visits the web page for the first time, a cookie is created on its machine and the same cookie is retrieved if the user is visiting for the second time. This helps us to check the status of the user. We are setting the expiration date of a cookie to 1 year for a persistent cookie to be available on the client machine. The image shows the visiting history of a user for the first time and second time. Please note the welcome message is changed in both of the visits.
A Query String (or HTTP Query String) is the information that is appended to the end of a URL. It is commonly used to pass data from one page to another through the URL. In a URL, the query string follows a separating character, mostly a question mark
(?). Consider the following URL:
- It provides an easy way to pass information from one page to another.
- Nearly all the browsers and client devices support query strings.
- The information in the query string is directly visible to the user via the browser's user interface, therefore it cannot be used for sensitive data.
- The maximum length of a URL is 2083 characters in nearly all the common browsers. So, we can't append a large amount of information as a query string to the URL.
Real World Scenario
Login page, the User enters credentials and is ready to log into the website. If the credentials are correct, it should be redirected to another page, such as
Dashboard. Now, we want to transfer some information of the User from the Login page to the Dashboard page such as Username. This scenario can be easily done using Query String.
Let's say we want to display the username on the Dashboard page, that the user has entered during login. We can append the username with the URL using Query string and can retrieve the same on the Dashboard page.
Session State is a server-side State Management technique that allows us to store data for a specific user. It is used to store values for a limited duration of time. A unique Session ID is created for each session of the application. Session Ids are maintained either using Cookies or using a modified URL.
Session State is stored in an instance of the
HttpSessionState class. The scope of the values stored in a Session State is limited to a specific user and cannot be shared across multiple users of the site. The Session State supports the following modes to store data.
- InProc Mode
- State Server Mode
- SQL Server Mode
- Custom Mode
- Off Mode
- The scope of the Session State is limited to a specific user.
- It provides a secure way to store data across all pages of an application.
- It also works with browsers that doesn't support cookies.
- It stores data using the Server memory and can adversely affect performance if not handled properly.
Real World Scenario
In the Query String example, we use the query string to transfer user information from
Login page to the
Dashboard page. You've noticed that the username is appended to the URL and can be easily tampered with. It is not the recommended approach to transfer sensitive data. To transfer sensitive data, we need a secure approach and this is where Session State is useful. The session variables provide a better way to do the same situation using Server-Side state management.
The following image shows the same scenario using Session State. Note that there is no data appended to the URL that can be tampered with.
Application State is used to store data that needs to be available for the entire application. Application State is stored in the memory of the server. Unlike Session State, that is specific to a single user session, Application State applies to all users and sessions. The data stored in the Application State stays as long as the application is running and lost when your application is restarted or your web server restarts.
Application State is stored in an instance of the
HttpApplicationState class. This class is a named object collection, which means that it should hold data of any type as part of a key/value pair.
- The scope of the Application State is global. We can store data that can be accessed throughout the application.
- It does not have any default expiration period.
- Application State requires server resources to store data. This can lead to scalability issues if not handled properly.
- Application State is not thread safe, so we need to implement Locks.
- In the case of an application failure or restart, all the stored data is lost.
Real World Scenario
Suppose our website needs a counter to keep track of the number of online users. To implement the online counter, we can use Application State that is available throughout the application globally and store data on the server side as long as the website is running in the server or until the server is restarted.
The following image shows the counter on the Dashboard page that displays the number of active users. We make use of
Global.asax for the online counter.
The complete source code of the application is available on GitHub. I hope this article helps you to understand the various State Management techniques of ASP.NET. Your feedback and constructive criticism is always appreciated, keep it coming. Until then, try to put a ding in the universe!