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. 示範如何覆Load寫和Save方法, 以將檢視狀態資訊解壓縮並加以儲存。 StreamPageStatePersisterThe StreamPageStatePersister demonstrates how to override the Load and Save methods to extract and save view state information. 由於狀態持續性機制與適應性轉譯和用戶端功能相關, MyPageAdapter因此會提供類別來啟動 ASP.NET 應用程式的。 StreamPageStatePersisterBecause 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. 最後, 會提供瀏覽器功能 (. 瀏覽器) 檔案, 為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.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

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

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

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>檔中的元素會指出設定會覆寫預設瀏覽器設定檔案中為預設瀏覽器指定的值。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 網頁 (通常不會使用介面卡)。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 中的預設檢視狀態持續性機制, 是在頁面上將狀態資訊當做 Base64 編碼的字串, 在隱藏的 HTML 專案 ( 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. 若要在您的控制項中執行自訂狀態LoadViewState處理SaveViewState , 請覆寫和方法。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. 如果您需要將 view state 和 control 狀態序列化為字串, 您可以使用可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 的淺層複本 (Shallow Copy)。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)

適用於

另請參閱