PageStatePersister Classe
Definição
Fornece a funcionalidade básica para mecanismos de persistência de estado de exibição do 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
- Herança
-
PageStatePersister
- Derivado
Exemplos
O exemplo de código a seguir demonstra como criar um PageStatePersister objeto que salva o estado de controle e exibição no servidor Web.The following code example demonstrates how to create a PageStatePersister object that saves view and control state on the Web server. O StreamPageStatePersister demonstra como substituir os Load métodos e Save para extrair e salvar informações de estado de exibição.The StreamPageStatePersister demonstrates how to override the Load and Save methods to extract and save view state information. Como os mecanismos de persistência de estado estão relacionados à renderização adaptável e aos recursos do cliente, a MyPageAdapter classe é fornecida para ativar o StreamPageStatePersister para um aplicativo ASP.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. Por fim, um arquivo de recursos do navegador (. browser) é fornecido para habilitar o MyPageAdapter adaptador para uma classe específica de clientes (nesse caso, o navegador da Web padrão).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
O exemplo de código a seguir demonstra como criar uma PageAdapter classe que retorna uma instância do StreamPageStatePersister , que é usada para persistir o modo de exibição e o estado de controle de uma página da Web 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 essas duas classes em um assembly que você pode usar para executar uma amostra, usando a linha de comando do compilador a seguir.Compile these two classes into an assembly that you can use to run a sample, using the following compiler command line. Verifique se o assembly compilado está no diretório \bin abaixo da raiz do aplicativo ASP.NET.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
'
Por fim, para habilitar o MyPageAdapter adaptador, você deve criar um diretório chamado navegadores sob a raiz do aplicativo ASP.net e incluir um arquivo. browser com informações de configuração.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. O <refid> elemento no arquivo de configuração indica que a configuração substitui os valores especificados para o navegador padrão no arquivo de configuração padrão. 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. Neste exemplo, MyPageAdapter é usado para páginas da Web ASP.net (onde normalmente nenhum adaptador é usado).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>
Comentários
As solicitações e respostas HTTP são inerentemente sem monitoração de estado.The HTTP requests and responses are inherently stateless. Para manter informações de estado entre solicitações HTTP, as páginas do servidor ASP.NET podem armazenar o Page estado.To maintain state information between HTTP requests, ASP.NET server pages can store Page state. Esse Estado, chamado de estado de exibição, consiste em configurações de página e controle e dados que fazem com que a página e os controles apareçam como se fossem os mesmos que o usuário viu e interagir na última viagem de ida e volta para o servidor.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. Existem vários mecanismos para armazenar o estado de exibição entre solicitações sucessivas na mesma página.Several mechanisms exist to store view state between successive requests to the same page. A PageStatePersister classe abstract representa a classe base para esses mecanismos de armazenamento de informações de estado.The abstract PageStatePersister class represents the base class for these state information storage mechanisms.
O mecanismo de persistência do estado de exibição padrão em ASP.NET é manter as informações de estado como uma cadeia de caracteres codificada em base64 em um elemento HTML oculto (um elemento com o type atributo definido como "hidden" ) na página.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. Uma página ASP.NET usa um HiddenFieldPageStatePersister objeto para executar esse trabalho, usando uma IStateFormatter instância para serializar e desserializar informações de estado do objeto.An ASP.NET page uses a HiddenFieldPageStatePersister object to perform this work, using an IStateFormatter instance to serialize and deserialize object state information. Como alternativa, você pode armazenar o estado de exibição para suas páginas no Session objeto no servidor usando a SessionPageStatePersister classe para clientes móveis com largura de banda e recursos limitados.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. Em alguns casos, você pode desabilitar completamente a persistência do estado de exibição.In some cases, you might disable view state persistence altogether. Se você fizer isso, o resultado será que, às vezes, as páginas e os controles que dependem da persistência de estado não se comportam corretamente.If you do this, the result is that sometimes pages and controls that rely on state persistence do not behave correctly. Para obter mais informações sobre gerenciamento de estado de página e estado de exibição, consulte visão geral do gerenciamento de estado ASP.net.For more information about page state management and view state, see ASP.NET State Management Overview.
Se você estiver escrevendo controles, poderá armazenar informações de estado para os controles no ViewState dicionário, que é um StateBag objeto.If you are writing controls, you can store state information for the controls in the ViewState dictionary, which is a StateBag object. Um desenvolvedor recuperaria o estado de controle por meio da ControlState propriedade.A developer would retrieve the control state through the ControlState property. Você atribui chaves e valores à ViewState propriedade, e o Page objeto serializa as informações de estado entre solicitações.You assign keys and values to the ViewState property, and the Page object serializes the state information between requests. Para executar o tratamento de estado personalizado em seu controle, substitua os LoadViewState SaveViewState métodos e.To perform custom state handling in your control, override the LoadViewState and SaveViewState methods. Todas as informações de estado armazenadas nesse dicionário são perdidas quando o estado de exibição é desabilitado por um desenvolvedor de página.Any state information that is stored in this dictionary is lost when view state is disabled by a page developer. Para atenuar isso, no ASP.NET versão 2,0, você pode armazenar informações de estado crítico em um objeto separado, chamado Estado de controle.To mitigate this, in ASP.NET version 2.0 you can store critical state information in a separate object, called control state. O objeto de estado de controle não é afetado quando o estado de exibição é desabilitado por um desenvolvedor de página.The control state object is not affected when view state is disabled by a page developer. Armazenar informações de estado no objeto de estado de controle requer que o controle substitua os LoadControlState SaveControlState métodos e e que o controle seja registrado para armazenar informações de estado no estado de controle sempre que o controle for inicializado.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. Você pode registrar um controle para usar o estado de controle substituindo o OnInit método e chamando o RegisterRequiresControlState método.You can register a control to use control state by overriding the OnInit method and calling the RegisterRequiresControlState method. Para obter mais informações sobre como usar a ViewState propriedade e o estado de controle ao desenvolver controles, consulte desenvolvendo controles de servidor ASP.NET personalizados.For more information about using the ViewState property and control state when developing controls, see Developing Custom ASP.NET Server Controls.
Para manter o estado de exibição em clientes que não dão suporte aos mecanismos de persistência de estado de exibição existentes, você pode estender a PageStatePersister classe para apresentar seus próprios métodos de persistência de estado de exibição e pode usar adaptadores de página para configurar seu aplicativo ASP.net para usar mecanismos de persistência de estado de exibição diferentes com base no tipo de cliente para o qual uma página é servida.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. As classes que derivam da PageStatePersister classe devem substituir o Save método abstract para armazenar o estado de exibição e o estado de controle no meio de persistência e substituir o Load método para extraí-lo.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. Se você precisar serializar o estado de exibição e o estado de controle para uma cadeia de caracteres, poderá usar o IStateFormatter objeto que é acessado usando a StateFormatter propriedade.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. Ele serializa e desserializa com eficiência as informações de estado do objeto para uma cadeia de caracteres codificada em base64.It efficiently serializes and deserializes object state information to a Base64-encoded string. Você também pode substituir a StateFormatter propriedade para fornecer seu próprio mecanismo de serialização de estado de objeto.You can also override the StateFormatter property to supply your own object state serialization mechanism.
Construtores
| PageStatePersister(Page) |
Inicializa uma nova instância da classe PageStatePersister.Initializes a new instance of the PageStatePersister class. |
Propriedades
| ControlState |
Obtém ou define um objeto que representa os dados que controla, contidos pelo objeto Page atual que usa para persistir em solicitações HTTP ao servidor Web.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 |
Obtém ou define o objeto Page para o qual o mecanismo de persistência de estado de exibição é criado.Gets or sets the Page object that the view state persistence mechanism is created for. |
| StateFormatter |
Obtém um objeto IStateFormatter que é usado para serializar e desserializar as informações de estado contidas nas propriedades ViewState e ControlState durante as chamadas aos métodos Save() e 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 |
Obtém ou define um objeto que representa os dados que controla, contidos pelo objeto Page atual que usa para persistir em solicitações HTTP ao servidor Web.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. |
Métodos
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| Load() |
Substituído por classes derivadas para desserializar e carregar as informações de estado persistente quando um objeto Page inicializa sua hierarquia de controle.Overridden by derived classes to deserialize and load persisted state information when a Page object initializes its control hierarchy. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| Save() |
Substituído por classes derivadas para serializar informações de estado persistente quando um objeto Page é descarregado da memória.Overridden by derived classes to serialize persisted state information when a Page object is unloaded from memory. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |