State Management in ASP.NET: Everything You Need to Know

Introduction

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 a 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 all these state management techniques.

Getting Started


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 and create an empty web application and name it “StateManagementDemo”.



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 Demo.aspx.



I'm sure all of you are familiar with HTML Controls and Server Controls in ASP.NET. Read here for more information. 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.

  1. 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
    • Cookies
    • Query String
    • Control State
    • Hidden Fields

  2. 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, a Developer's Cafe. The website contains two pages, Login and 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 GitHub account.

Note: Please note that the real world scenario I present 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.

  1. View State

    Definition


    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 false.

    Advantages

    1. View State is the default mechanism of ASP.NET Server controls to retain states during round trips.
    2. It is a dictionary type of the State Bag collection class and can be used to store any type of data.
    3. It is a perfect place to store data that is used for multiple post backs in a single web page.

    Disadvantages

    1. 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.
    2. The information stored in View state is not encrypted and can be easily tampered with by anyone. So it cannot be used to store any sensitive data.
    3. 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

    In our 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 form. 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 in into the website.



  2. Cookie

    Definition


    A cookie is a client-side 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 and Non-Persistent cookie.

    1. 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.
    2. 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.

    Advantages

    1. It is very simple and easy to use.
    2. It takes only a few bytes of memory to create a cookie.

    Disadvantages

    1. Cookies can be easily disabled by a user by tweaking the browser settings.
    2. 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.
    3. 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.



  3. Query String

    Definition


    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:

    http://www.developerscafe.com/Dashboard.aspx?username=admin

    Advantages

    1. It provides an easy way to pass information from one page to another.
    2. Nearly all the browsers and client devices support query strings.

    Disadvantages

    1. 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.
    2. 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

    In the 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.aspx. Now, I 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.



  4. Session State

    Definition


    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

    Advantages

    1. The scope of the Session State is limited to a specific user.
    2. It provides a secure way to store data across all pages of an application.
    3. It works with browsers that don't support cookies.

    Disadvantages

    1. 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.


5. Application State:

Definition

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.

Advantages

  1. The scope of the Application State is global. We can store data that can be accessed throughout the application.
  2. It does not have any default expiration period.

Disadvantages

  1. Application State requires server resources to store data. This can lead to scalability issues if not handled properly.
  2. Application State is not thread safe, so we need to implement Locks.
  3. 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 to do the online counter.



Conclusion

The complete source code of the application can be downloaded from my GitHub account. The real world scenario presented in this article is just for understanding purposes. There are several selection criteria to be considered before using State Management techniques since each of them has its own advantages as well as disadvantages.

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!

 
Article Update

This article is featured as 'Article of the Day' on Microsoft's official ASP.NET website [http://www.asp.net/community/articles] on 24-Dec-2014.

Up Next
    Ebook Download
    View all
    Learn
    View all