State Management in Web Forms

Abstract

This white paper discusses the ways in which the state management can be handled in web forms. State management can be done either on client side or server side as explained below.

1. Introduction to Web Forms State Management

Due to the nature of the standard transfer protocol ( http ), Web pages are regenerated each time the page is posted to the server ,because of which all information associated with the page, such as the values of controls contained within the page, would be lost with each round trip from the browser to the server and back.
To overcome this inherent limitation, automatic state management facilities provided by the framework, which basically involve storing information either on the client or on the server, are used.

2. State Management Recommendations

What is State Management? State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. Furthermore, pages are destroyed and recreated with each round trip to the server; therefore page information will not exist beyond the life cycle of a single page.

ASP.NET provides multiple ways to maintain state between server round trips. Choosing among the options for state management available in ASP.NET will depend heavily upon your application, and it should be based on the following criteria:

  • How much information do you need to store? 
  • Does the client accept persistent or in-memory cookies? 
  • Do you want to store the information on the client or server? 
  • Is the information sensitive? 
  • What sorts of performance criteria do you have for your application?

ASP.NET supports various client-side and server-side options for state management.

Client-side options are:

  • The View State property
  • Hidden fields
  • Cookies
  • Query strings

Server-side options are:

  • Application state
  • Session state
  • Database

a) Client-Based State Management Recommendations

The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.

1. View State

The Control.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips.

When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.

The advantages of using view state are:

  • No server resources required. The view state is contained in a structure within the page code.
  • Implementation is Simple.
  • Automatic retention of page and control state.
  • Enhanced security features. The values in view state are hashed, compressed, and encoded for Unicode implementations, thus representing a higher state of security than hidden fields have.

The disadvantages of using the view state are:

  • Performance. Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
  • Security. The view state is stored in a hidden field on the page. Although view state stores data in a hashed format, it can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.

2. Hidden Form Fields

ASP.NET allows you to use HTML-standard hidden fields in a form. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you would like to store directly in the page.

A hidden field stores a single variable in its value property and must be explicitly added to the page. Then you insert your value into the hidden field.

ASP.NET provides the HtmlInputHidden control that offers hidden field functionality. In order for hidden field values to be available during page processing, you must submit the page using an HTTP post method. That is, you cannot take advantage of hidden fields if a page is processed in response to a link or HTTP GET method .
The advantages of using hidden fields are:

  • No server resources are required. The hidden field is stored and read from the page.
  • Broad support. Almost all browsers and client devices support forms with hidden fields.
  • Simple implementation.

The disadvantages of using hidden fields are:

  • Security. The hidden field can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.
  • Limited storage structure. The hidden field does not support rich structures. Hidden fields offer a single value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings.
  • Performance. Because hidden fields are stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.

3. Cookies

A cookie is a small amount of data stored either in a text file on the client's file system or in-memory in the client browser session. It contains page-specific information the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, it sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
The browser can only send the data back to the server that originally created the cookie. Therefore, cookies are a relatively secure way of maintaining user-specific data.

The advantages of using cookies are:

  • No server resources are required. The cookie is stored on the client and read by the server after a post.
    Simplicity. The cookie is a lightweight, text-based structure with simple key-value pairs.
  • Configurable expiration. The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.

The disadvantages of using cookies are:

  • Limited size. Most browsers place a 4096-byte limit on the size of a cookie, although the support for 8192-byte cookie size is becoming common in the new browser and client-device versions available today.
  • User-configured refusal. Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
  • Security. Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially represent a security compromise or cause the application dependent on the cookie to fail.
  • Durability. The durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention.

4. Query Strings

A query string is information appended to the end of a page's URL. For example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100

In the URL path above, the query string starts with the question mark (?) and includes two attribute-value pairs, one called "category" and the other called "price."

Query strings provide a simple but limited way of maintaining some state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.

In order for query string values to be available during page processing, you must submit the page using an HTTP get method. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP post method.

The advantages of using query strings are:

  • No server resources required. The query string is contained in the HTTP request for a specific URL.
  • Broad support. Almost all browsers and client devices support passing values in a query string.
  • Simple implementation. ASP.NET provides full support for the query string method, including methods of reading query strings using the HttpRequest.Params property.

The disadvantages of using query strings are:

  • Security. The information in the query string is directly visible to the user via the browser user interface. The query values are exposed to the Internet via the URL so in some cases security may be an issue.
  • Limited capacity. Most browsers and client devices impose a 255-character limit on URL length.

b) Server-Based State Management Recommendations

Server-side options for storing page information tend to have higher security than client-side options, but they can use more Web server resources, which may lead to scalability issues when the size of the information store is large. ASP.NET provides several options to implement server-side state management.
ASP.NET offers you a variety of ways to maintain state information on the server, as described in the following sections.

1. Application State

ASP.NET allows you to save values using application state (an instance of the HttpApplicationState class) for each active Web application. Application state is a global storage mechanism accessible from all pages in the Web application and is thus useful for storing information that needs to be maintained between server round trips and between pages.

Application state is a key-value dictionary structure created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.
Once you add your application-specific information to application state, the server manages it.

The advantages of using application state are:

  • Ease of implementation. Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  • Global scope. Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information ( for instance, as opposed to keeping copies of information in session state or in individual pages ).

The disadvantages of using application state are:

  • Global scope. The global nature of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm configurations.
  • Durability. Because global data stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, most likely from a server crash, upgrade, or shutdown.
  • Resource requirements. Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.

2. Session State

ASP.NET allows you to save values using session state, which is an instance of the HttpSessionState class for each active Web application session.

Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each will have a different session state. In addition, if the same user leaves your application and then returns later, that user will also have a different session state.
Session state is structured as a key-value dictionary structure for storing session-specific information that needs to be maintained between server round trips and between requests for pages. For more information, see Session State.

Session state enables you to:

  • Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
  • Store session-specific data on the server for use across multiple browser or client-device requests within the same session.
  • Raise appropriate session management events. In addition, you can write application code leveraging these events.
  • Once you add your application-specific information to session state, the server manages this object. Depending on what options you specify, session information can be stored in cookies, an out-of-process server, or a SQL Server.

The advantages of using session state are:

  • Ease of implementation. The session state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  • Session-specific events. Session management events can be raised and used by your application.
  • Durability. Data placed in session-state variables can survive Internet Information Services ( IIS ) restarts and worker-process restarts without losing session data because the data is stored in another process space.
  • Platform scalability. Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  • Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application.

The disadvantage of using session state is:

  • Performance. Session state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session state variables containing blocks of information like large datasets can adversely affect Web server performance as server load increases.

3. Database Support

Maintaining state using database technology is a common practice when storing user-specific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted.

The database approach is often used in conjunction with cookies. For example, when a user first accesses your application, you might have the user log in. You can look up the user in your database and then pass a cookie to the user. The cookie might contain only the ID of the user in your database ( for example, a customer number ). You can then use the cookie in subsequent requests to find the user information in the database as needed.

The database support approach enables you to:

  • Uniquely identify browser or client-device requests and map them to a unique ID.
  • Maintain state by relating stored information to the unique ID. You can use the unique ID to query the database for information relating to that ID. You can then modify the information and save it back to the database for use across multiple requests for the same or different pages in your site. Raise appropriate events. A condition in the database may determine site action. For example, if the user of a commerce site attempts to purchase something that is not in stock, a database query may signal that the Web site should prompt the user to make another selection.

In some cases, you may wish to use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is quite common for an e-commerce Web site to maintain state information using a relational database for the following reasons:

  • Security
  • Personalization
  • Consistency
  • Data mining

The following are typical features of a cookie-supported database Web site:

Security:

The visitor types an account name and password into a site logon page. The site infrastructure queries the database with the logon values to determine if the user has rights to utilize your site. If the database validates the user information, the Web site will distribute a valid cookie containing a unique ID for that user on that client computer. The site grants access to the user.

Personalization:

With security information in place, your site is able to distinguish each user on your site by reading the cookie on the client computer. Typically, sites have information in the database that describes the preferences of a user ( identified by a unique ID ). This relationship is known as personalization. The site can research the user's preferences using the unique ID contained in the cookie, and then place content and information in front of the user that pertains to the user's specific wishes and reacts to the user's preferences over time.

Consistency:

If you have created a commerce Web site, you may wish to keep transactional records of purchases made for goods and services on your site. This information can be reliably saved in your database and referenced by the user's unique ID. It can be used to determine if a purchase transaction has been completed, and also to determine the course of action should a purchase transaction fail. The information may also be used to inform the user of the status of an order placed using your site.

Data mining:

Information about your site usage, your visitors, or your product transactions can be reliably stored in your database. For example, your business development department may wish to use this data collected from your site to determine next year's product line or distribution policy. Your marketing department may wish to examine demographic information about users on your site. Your engineering and support department may wish to look at transactions and note areas where your purchasing process could be improved. Most enterprise-level relational databases such as Microsoft SQL Server contain an expansive toolset for most data mining projects.
By designing the Web site to repeatedly query the database by using the unique ID during each general stage in the above scenario, the site maintains state. In this way, the user perceives that the site is remembering and reacting to him or her personally.

The advantages of using a database to maintain state are:

  • Security. Access to databases is typically very secure, requiring rigorous authentication and authorization.
  • Capacity. You can store as much information as you like in a database.
  • Persistence. Database information can be stored as long as you like, and it is not subject to the availability of the Web server.
  • Robustness and data integrity. Databases include various facilities for maintaining good data, including triggers and referential integrity, transactions, and so on. By keeping information about transactions in a database ( rather than in session state, for example ), you can recover from errors more readily.
  • Accessibility. The data stored in your database is accessible to a wide variety of information-processing tools.
  • Wide support. There is a large range of database tools available, and many custom configurations are available.

The disadvantages of using a database to maintain state are:

  • Complexity. Using a database to support state management implies more complex hardware and software configurations.
  • Performance. Poor construction of the relational data model can lead to scaling issues. Also, leveraging too many queries to the database can adversely affect server performance.