Partager via


How to: Read Values from Application State

Application state is a data repository that is available to all classes within an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving data in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another.

Application state is stored in the HttpApplicationState class, a new instance of which is created the first time a user accesses a URL resource within an application. For more information, see ASP.NET Application State Overview.

Application state stores data typed as Object. Therefore, even though you do not have to serialize the data when storing it in application state, you must cast the data to the appropriate type when retrieving it. Although you can cast a null (Nothing in Visual Basic) object, if you attempt to use a non-existent application-state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

Procedure

To read a value from application state

  • Determine whether the application variable exists, and then convert the variable to the appropriate type when you access it.

    The following code example retrieves the application state AppStartTime value and converts it to a variable named appStateTime of type DateTime.

    If (Not Application("AppStartTime") Is Nothing) Then
        Dim myAppStartTime As DateTime = _
            CDate(Application("AppStartTime"))
    End If
    
    if (Application["AppStartTime"] != null)
    {
        DateTime myAppStartTime = (DateTime)Application["AppStartTime"];
    }
    

See Also

Tasks

How to: Save Values in Application State

Concepts

ASP.NET Application State Overview

ASP.NET State Management Overview

ASP.NET State Management Recommendations