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
. Query strings
Server-side options are:
. Application state
. Session state
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.
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.
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:
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.
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.