PageStatePersister PageStatePersister PageStatePersister PageStatePersister Class

定義

提供 ASP.NET 檢視狀態保存性機制的基本功能。Provides the base functionality for ASP.NET view state persistence mechanisms.

public ref class PageStatePersister abstract
public abstract class PageStatePersister
type PageStatePersister = class
Public MustInherit Class PageStatePersister
繼承
PageStatePersisterPageStatePersisterPageStatePersisterPageStatePersister
衍生

範例

下列程式碼範例示範如何建立PageStatePersister將檢視和控制項的狀態儲存在 Web 伺服器的物件。The following code example demonstrates how to create a PageStatePersister object that saves view and control state on the Web server. StreamPageStatePersister示範如何覆寫LoadSave方法來擷取並儲存檢視狀態資訊。The StreamPageStatePersister demonstrates how to override the Load and Save methods to extract and save view state information. 因為狀態持續性機制相關適應性呈現和用戶端的功能,所以MyPageAdapter類別會提供啟用StreamPageStatePersisterASP.NET 應用程式。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. 最後,瀏覽器的功能 (.browser) 檔案,可讓MyPageAdapter特定類別的用戶端 (在此案例中,預設網頁瀏覽器) 的配接器。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;
        }
    }
}
Imports System
Imports System.IO
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI

Namespace Samples.AspNet.VB

    ' 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
        Inherits PageStatePersister


        Public Sub New(ByVal page As Page)
            MyBase.New(page)
        End Sub 'New

        '
        ' Load ViewState and ControlState.
        '
        Public Overrides Sub Load()

            Dim stateStream As Stream
            stateStream = GetSecureStream()

            ' Read the state string, using the StateFormatter.
            Dim reader As New StreamReader(stateStream)

            Dim serializedStatePair As String
            serializedStatePair = reader.ReadToEnd
            Dim statePair As Pair

            Dim formatter As IStateFormatter
            formatter = Me.StateFormatter

            ' Deserilize returns the Pair object that is serialized in
            ' the Save method.      
            statePair = CType(formatter.Deserialize(serializedStatePair), Pair)

            ViewState = statePair.First
            ControlState = statePair.Second
            reader.Close()
            stateStream.Close()
        End Sub ' Load

        '
        ' Persist any ViewState and ControlState.
        '
        Public Overrides Sub Save()

            If Not (ViewState Is Nothing) OrElse Not (ControlState Is Nothing) Then
                If Not (Page.Session Is Nothing) Then

                    Dim stateStream As Stream
                    stateStream = GetSecureStream()

                    ' Write a state string, using the StateFormatter.
                    Dim writer As New StreamWriter(stateStream)

                    Dim formatter As IStateFormatter
                    formatter = Me.StateFormatter

                    Dim statePair As New Pair(ViewState, ControlState)

                    Dim serializedState As String
                    serializedState = formatter.Serialize(statePair)

                    writer.Write(serializedState)
                    writer.Close()
                    stateStream.Close()
                Else
                    Throw New InvalidOperationException("Session needed for StreamPageStatePersister.")
                End If
            End If
        End Sub 'Save
        ' Return a secure Stream for your environment.
        Private Function GetSecureStream() As Stream
            ' You must provide the implementation to build
            ' a secure Stream for your environment.
            Return Nothing
        End Function
    End Class
End Namespace

下列程式碼範例示範如何建立PageAdapter傳回的執行個體的類別StreamPageStatePersister,用以保存為 ASP.NET 網頁的檢視和控制項狀態。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);
        }
    }
}
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI

Namespace Samples.AspNet.VB

    <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
    Public Class MyPageAdapter
       Inherits System.Web.UI.Adapters.PageAdapter


       Public Overrides Function GetStatePersister() As PageStatePersister
          Return New Samples.AspNet.VB.StreamPageStatePersister(Page)
       End Function 'GetStatePersister

    End Class 'MyPageAdapter

End Namespace

編譯為組件可供您執行範例,使用下列的編譯器命令列中的這兩個類別。Compile these two classes into an assembly that you can use to run a sample, using the following compiler command line. 請確定已編譯的組件是在 ASP.NET 應用程式根目錄下的 \Bin 目錄中。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:\>
' C:\>vbc /t:library /out:C:\inetpub\wwwroot\bin\Samples.AspNet.VB.dll MyPageAdapter.vb TextFilePageStatePersister.vb
'

最後,若要啟用MyPageAdapter配接器,您必須建立名為 ASP.NET 應用程式根目錄中,下方的瀏覽器,並包含.browser 檔案具有組態資訊。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. <refid>組態檔中的項目可讓您指示,設定會覆寫預設的瀏覽器 Default.browser 組態檔中指定的值。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. 在此範例中,MyPageAdapter用於 ASP.NET Web pages (其中通常沒有配接器會使用)。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>  

備註

HTTP 要求和回應是原本就是無狀態。The HTTP requests and responses are inherently stateless. 若要維護狀態資訊之間的 HTTP 要求,ASP.NET 伺服器頁面可以儲存Page狀態。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. 抽象PageStatePersister類別代表這些狀態資訊的儲存機制的基底類別。The abstract PageStatePersister class represents the base class for these state information storage mechanisms.

預設檢視狀態保存性機制,在 ASP.NET 中的是要維持為隱藏的 HTML 項目中的 Base64 編碼字串的狀態資訊 (具有的項目type屬性設為"hidden") 頁面上。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. ASP.NET 網頁會使用HiddenFieldPageStatePersister物件來執行此工作,使用IStateFormatter序列化和還原序列化物件狀態資訊的執行個體。An ASP.NET page uses a HiddenFieldPageStatePersister object to perform this work, using an IStateFormatter instance to serialize and deserialize object state information. 或者,您可以檢視狀態儲存在頁面Session伺服器上的物件SessionPageStatePersister供行動用戶端具有有限的頻寬和資源的類別。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. 如需有關頁面狀態管理和檢視狀態的詳細資訊,請參閱ASP.NET 狀態管理概觀For more information about page state management and view state, see ASP.NET State Management Overview.

如果您正在撰寫控制項,您可以儲存在控制項狀態資訊ViewState字典中,也就是StateBag物件。If you are writing controls, you can store state information for the controls in the ViewState dictionary, which is a StateBag object. 開發人員會擷取到的控制項狀態ControlState屬性。A developer would retrieve the control state through the ControlState property. 您將指定的索引鍵和值ViewState屬性,而Page物件序列化要求之間的狀態資訊。You assign keys and values to the ViewState property, and the Page object serializes the state information between requests. 若要執行自訂控制項中處理的狀態,請覆寫LoadViewStateSaveViewState方法。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. 為了減輕這個在 ASP.NET 中您可以將重大狀態資訊儲存在個別的物件,稱為控制項狀態的 2.0 版。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. 將狀態資訊儲存在控制項的狀態物件需要控制項覆寫LoadControlStateSaveControlState方法和控制項登錄來儲存狀態資訊在控制狀態每次初始化控制項時。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. 您可以註冊要使用控制項狀態,藉由覆寫控制項OnInit方法,並呼叫RegisterRequiresControlState方法。You can register a control to use control state by overriding the OnInit method and calling the RegisterRequiresControlState method. 如需使用詳細資訊ViewState屬性和控制項狀態,當開發控制項,請參閱開發自訂 ASP.NET 伺服器控制項For more information about using the ViewState property and control state when developing controls, see Developing Custom ASP.NET Server Controls.

若要維護檢視狀態無法支援現有的用戶端檢視狀態保存性機制,您可以擴充PageStatePersister引進您自己的檢視狀態持續性方法、 類別和您可以使用 頁面配置器來設定 ASP.NET 應用程式若要使用不同的檢視狀態保存性機制,提供頁面時的用戶端的類型為基礎。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. 衍生自類別PageStatePersister類別必須覆寫抽象Save方法,以將檢視狀態和控制項狀態儲存在持續性媒體,並覆寫Load方法,以將它解壓縮。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. 如果您需要序列化檢視狀態和控制項狀態的字串,您可以使用IStateFormatter物件,可使用StateFormatter屬性。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. 有效率的方式,其會序列化和還原序列化為 Base64 編碼字串的物件狀態資訊。It efficiently serializes and deserializes object state information to a Base64-encoded string. 您也可以覆寫StateFormatter屬性,來提供您自己的物件狀態的序列化機制。You can also override the StateFormatter property to supply your own object state serialization mechanism.

建構函式

PageStatePersister(Page) PageStatePersister(Page) PageStatePersister(Page) PageStatePersister(Page)

初始化 PageStatePersister 類別的新執行個體。Initializes a new instance of the PageStatePersister class.

屬性

ControlState ControlState ControlState ControlState

取得或設定物件,表示對 Web 伺服器的 HTTP 要求之間,目前 Page 物件所包含的控制項用以保存的資料。Gets 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.

Page Page Page Page

取得或設定 Page 物件,以建立檢視狀態保存性機制。Gets or sets the Page object that the view state persistence mechanism is created for.

StateFormatter StateFormatter StateFormatter StateFormatter

取得 IStateFormatter 物件,對 ViewStateControlState 方法呼叫時,這個物件會用來序列化和還原序列化 Save()Load() 屬性中包含的狀態資訊。Gets 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.

ViewState ViewState ViewState ViewState

取得或設定物件,表示對 Web 伺服器的 HTTP 要求之間,目前 Page 物件所包含的控制項用以保存的資料。Gets 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.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
Load() Load() Load() Load()

Page 物件初始化其控制階層架構時,由衍生類別覆寫,以還原序列化並載入保存的狀態資訊。Overridden by derived classes to deserialize and load persisted state information when a Page object initializes its control hierarchy.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
Save() Save() Save() Save()

從記憶體卸載 Page 物件時,由衍生類別覆寫,以序列化保存的狀態資訊。Overridden by derived classes to serialize persisted state information when a Page object is unloaded from memory.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

適用於

另請參閱