Export (0) Print
Expand All

PageStatePersister Class

Provides the base functionality for ASP.NET view state persistence mechanisms.

Namespace:  System.Web.UI
Assembly:  System.Web (in System.Web.dll)

public abstract class PageStatePersister

The PageStatePersister type exposes the following members.

  NameDescription
Protected methodPageStatePersisterInitializes a new instance of the PageStatePersister class.
Top

  NameDescription
Public propertyControlStateGets or sets an object that represents the data that controls contained by the current Page object use to persist across HTTP requests to the Web server.
Protected propertyPageGets or sets the Page object that the view state persistence mechanism is created for.
Protected propertyStateFormatterGets an IStateFormatter object that is used to serialize and deserialize the state information contained in the ViewState and ControlState properties during calls to the Save and Load methods.
Public propertyViewStateGets or sets an object that represents the data that controls contained by the current Page object use to persist across HTTP requests to the Web server.
Top

  NameDescription
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodLoadOverridden by derived classes to deserialize and load persisted state information when a Page object initializes its control hierarchy.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSaveOverridden by derived classes to serialize persisted state information when a Page object is unloaded from memory.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

The HTTP requests and responses are inherently stateless. To maintain state information between HTTP requests, ASP.NET server pages can store Page state. This state, called view state, consists of page and control settings and data that make the page and controls appear as if they are the same ones that the user saw and interacted with on their last round trip to the server. Several mechanisms exist to store view state between successive requests to the same page. The abstract PageStatePersister class represents the base class for these state information storage mechanisms.

The default view state persistence mechanism in ASP.NET is to maintain the state information as a Base64-encoded string in a hidden HTML element (an element with the type attribute set to "hidden") on the page. An ASP.NET page uses a HiddenFieldPageStatePersister object to perform this work, using an IStateFormatter instance to serialize and deserialize object state information. Alternately, you can store the view state for your pages in the Session object on the server using the SessionPageStatePersister class for mobile clients with limited bandwidth and resources. In some cases, you might disable view state persistence altogether. If you do this, the result is that sometimes pages and controls that rely on state persistence do not behave correctly. For more information about page state management and view state, see ASP.NET State Management Overview.

If you are writing controls, you can store state information for the controls in the ViewState dictionary, which is a StateBag object. A developer would retrieve the control state through the ControlState property. You assign keys and values to the ViewState property, and the Page object serializes the state information between requests. To perform custom state handling in your control, override the LoadViewState and SaveViewState methods. Any state information that is stored in this dictionary is lost when view state is disabled by a page developer. To mitigate this, in ASP.NET version 2.0 you can store critical state information in a separate object, called control state. The control state object is not affected when view state is disabled by a page developer. Storing state information in the control state object requires that the control override the LoadControlState and SaveControlState methods and that the control be registered to store state information in control state every time the control is initialized. You can register a control to use control state by overriding the OnInit method and calling the RegisterRequiresControlState method. For more information about using the ViewState property and control state when developing controls, see Developing Custom ASP.NET Server Controls.

To maintain view state on clients that cannot support the existing view state persistence mechanisms, you can extend the PageStatePersister class to introduce your own view state persistence methods, and you can use page adapters to configure your ASP.NET application to use different view state persistence mechanisms based on the type of client to which a page is served. Classes that derive from the PageStatePersister class must override the abstract Save method to store view state and control state in the persistence medium, and override the Load method to extract it. If you need to serialize view state and control state to a string, you can use the IStateFormatter object that is accessed using the StateFormatter property. It efficiently serializes and deserializes object state information to a Base64-encoded string. You can also override the StateFormatter property to supply your own object state serialization mechanism.

The following code example demonstrates how to create a PageStatePersister object that saves view and control state on the Web server. The StreamPageStatePersister demonstrates how to override the Load and Save methods to extract and save view state information. Because the state persistence mechanisms are related to adaptive rendering and client capabilities, the MyPageAdapter class is provided to activate the StreamPageStatePersister for an ASP.NET application. Finally, a browser capabilities (.browser) file is provided to enable the MyPageAdapter adapter for a specific class of clients (in this case, the default Web browser).

namespace Samples.AspNet.CS
{

    using System;
    using System.IO;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI;

    // 
    // The StreamPageStatePersister is an example view state 
    // persistence mechanism that persists view and control 
    // state on the Web server. 
    //
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class StreamPageStatePersister : PageStatePersister
    {

        public StreamPageStatePersister(Page page)
            : base(page)
        {
        }
        // 
        // Load ViewState and ControlState. 
        // 
        public override void Load()
        {
            Stream stateStream = GetSecureStream();

            // Read the state string, using the StateFormatter.
            StreamReader reader = new StreamReader(stateStream);

            IStateFormatter formatter = this.StateFormatter;
            string fileContents = reader.ReadToEnd();

            // Deserilize returns the Pair object that is serialized in 
            // the Save method.
            Pair statePair = (Pair)formatter.Deserialize(fileContents);

            ViewState = statePair.First;
            ControlState = statePair.Second;
            reader.Close();
            stateStream.Close();
        }
        // 
        // Persist any ViewState and ControlState. 
        // 
        public override void Save()
        {

            if (ViewState != null || ControlState != null)
            {
                if (Page.Session != null)
                {
                    Stream stateStream = GetSecureStream();

                    StreamWriter writer = new StreamWriter(stateStream);

                    IStateFormatter formatter = this.StateFormatter;
                    Pair statePair = new Pair(ViewState, ControlState);

                    // Serialize the statePair object to a string. 
                    string serializedState = formatter.Serialize(statePair);

                    writer.Write(serializedState);
                    writer.Close();
                    stateStream.Close();
                }
                else 
                    throw new InvalidOperationException("Session needed for StreamPageStatePersister.");
            }
        }
        // Return a secure Stream for your environment. 
        private Stream GetSecureStream()
        {
            // You must provide the implementation to build 
            // a secure Stream for your environment. 
            return null;
        }
    }
}

The following code example demonstrates how to create a PageAdapter class that returns an instance of StreamPageStatePersister, which is used to persist view and control state for an ASP.NET Web page.

namespace Samples.AspNet.CS {

    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI;

    [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Minimal)]
    public class MyPageAdapter : System.Web.UI.Adapters.PageAdapter {

        public override PageStatePersister GetStatePersister() {
            return new Samples.AspNet.CS.StreamPageStatePersister(Page);
        }
    }
}

Compile these two classes into an assembly that you can use to run a sample, using the following compiler command line. Ensure that the compiled assembly is in the \Bin directory underneath the ASP.NET application root.

// C:\>csc /t:library /out:C:\inetpub\wwwroot\bin\Samples.AspNet.CS.dll MyPageAdapter.cs TextFilePageStatePersister.cs 
// 
// C:\>

Finally, to enable the MyPageAdapter adapter, you must create a directory named Browsers underneath the ASP.NET application root, and include a .browser file with configuration information. The <refid> element in the configuration file indicates that the configuration overrides the values specified for the default browser in the Default.browser configuration file. In this example, MyPageAdapter is used for ASP.NET Web pages (where normally no adapter is used).

<browsers>
    <browser refid="Default" >
        <controlAdapters>
            <adapter 
                controlType="System.Web.UI.Page"                            
                adapterType="Samples.AspNet.CS.MyPageAdapter" />
        </controlAdapters>
    </browser>
</browsers>

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft