IStateFormatter Интерфейс

Определение

Определяет методы, реализуемые типом для сериализации и десериализации графы объекта.

public interface class IStateFormatter
public interface IStateFormatter
type IStateFormatter = interface
Public Interface IStateFormatter
Производный

Примеры

В следующем примере кода показано, как создать PageStatePersister объект, который сохраняет состояние представления и элемента управления в поток на веб-сервере. В StreamPageStatePersister классе показано, как переопределить Load методы для Save извлечения и сохранения сведений о состоянии страницы. Эти методы используют интерфейс, IStateFormatter унаследованный от PageStatePersister класса, для сериализации и десериализации состояния представления. Этот пример кода является частью более крупного примера, предоставленного PageStatePersister для класса.

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

Комментарии

Интерфейс IStateFormatter определяет методы, которые тип может реализовать для сериализации и десериализации состояния, которое элемент управления веб-сервера ASP.NET поддерживает в своем ViewState свойстве. Эта инфраструктура используется классами, производными от PageStatePersister класса, для поддержания состояния страницы ASP.NET между запросами. По умолчанию ASP.NET состояние страницы сериализуется и десериализуется экземпляром ObjectStateFormatter класса, однако разработчики сайтов и адаптеров могут реализовать IStateFormatter интерфейс в своих собственных типах для выполнения этой работы.

Дополнительные сведения об управлении состоянием веб-сервера и состоянии просмотра см. в разделе ASP.NET Обзор управления состоянием, динамические веб-серверные элементы управления и состояние просмотра.

Методы

Deserialize(String)

Выполняет десериализацию графы состояния объекта из его сериализованной формы строки.

Serialize(Object)

Выполняет сериализацию состояния элемента управления ASP.NET веб-сервера в форму строки.

Применяется к

См. также раздел