ISessionIDManager Interface

Definição

Define o contrato que um gerenciador de identificador de estado de sessão personalizado deve implementar.Defines the contract that a custom session-state identifier manager must implement.

public interface class ISessionIDManager
public interface ISessionIDManager
type ISessionIDManager = interface
Public Interface ISessionIDManager
Derivado

Exemplos

O exemplo de código a seguir mostra uma classe que implementa um Gerenciador de ID de sessão baseado em cookie.The following code example shows a class that implements a cookie-based session-ID manager.

using System;
using System.Configuration;
using System.Web.Configuration;
using System.Web;
using System.Web.SessionState;

namespace Samples.AspNet.Session
{

  public class MySessionIDManager : IHttpModule, ISessionIDManager
  {

    private SessionStateSection pConfig = null;

    //
    // IHttpModule Members
    //

    //
    // IHttpModule.Init
    //

    public void Init(HttpApplication app)
    {
      // Obtain session-state configuration settings.

      if (pConfig == null)
      {
        Configuration cfg =
          WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
        pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");
      }
    }

    //
    // IHttpModule.Dispose
    //

    public void Dispose()
    {
    }

    //
    // ISessionIDManager Members
    //

    //
    // ISessionIDManager.Initialize
    //

    public void Initialize()
    {
    }

    //
    // ISessionIDManager.InitializeRequest
    //

    public bool InitializeRequest(HttpContext context, 
                                  bool suppressAutoDetectRedirect, 
                                  out bool supportSessionIDReissue)
    {
      if (pConfig.Cookieless == HttpCookieMode.UseCookies)
      {
        supportSessionIDReissue = false;
        return false;
      }
      else
      {
        supportSessionIDReissue = true;
        return context.Response.IsRequestBeingRedirected;
      }
    }

    //
    // ISessionIDManager.GetSessionID
    //
    public string GetSessionID(HttpContext context)
    {
      string id = null;

      if (pConfig.Cookieless == HttpCookieMode.UseUri)
      {
        // Retrieve the SessionID from the URI.
      }
      else
      {
        id = context.Request.Cookies[pConfig.CookieName].Value;
      }      

      // Verify that the retrieved SessionID is valid. If not, return null.

      if (!Validate(id))
        id = null;

      return id;
    }

    //
    // ISessionIDManager.CreateSessionID
    //

    public string CreateSessionID(HttpContext context)
    {
      return Guid.NewGuid().ToString();
    }

    //
    // ISessionIDManager.RemoveSessionID
    //

    public void RemoveSessionID(HttpContext context)
    {
      context.Response.Cookies.Remove(pConfig.CookieName);
    }

    //
    // ISessionIDManager.SaveSessionID
    //

    public void SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
    {
      redirected = false;
      cookieAdded = false;

      if (pConfig.Cookieless == HttpCookieMode.UseUri)
      {
        // Add the SessionID to the URI. Set the redirected variable as appropriate.

        redirected = true;
        return;
      }
      else
      {
        context.Response.Cookies.Add(new HttpCookie(pConfig.CookieName, id));
        cookieAdded = true;
      }
    }

    //
    // ISessionIDManager.Validate
    //

    public bool Validate(string id)
    {
      try
      {
        Guid testGuid = new Guid(id);

        if (id == testGuid.ToString())
          return true;
      }
      catch
      {
      }

      return false;
    }
  }
}
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Web
Imports System.Web.SessionState


Namespace Samples.AspNet.Session


  Public Class MySessionIDManager
    Implements IHttpModule, ISessionIDManager

    Private pConfig As SessionStateSection = Nothing

    '
    ' IHttpModule Members
    '

    '
    ' IHttpModule.Init
    '

    Public Sub Init(app As HttpApplication) Implements IHttpModule.Init
    
      ' Obtain session-state configuration settings.

      If pConfig Is Nothing Then      
        Dim cfg As System.Configuration.Configuration = _
          WebConfigurationManager.OpenWebConfiguration( _
            System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath)
        pConfig = CType(cfg.GetSection("system.web/sessionState"), SessionStateSection)
      End If

    End Sub


    '
    ' IHttpModule.Dispose
    '

    Public Sub Dispose() Implements IHttpModule.Dispose
    
    End Sub



    '
    ' ISessionIDManager.Initialize
    '

    Public Sub Initialize() Implements ISessionIDManager.Initialize

    End Sub


    '
    ' ISessionIDManager.InitializeRequest
    '

    Public Function InitializeRequest(context As HttpContext,  _
                                      suppressAutoDetectRedirect As Boolean,  _
                                      ByRef supportSessionIDReissue As Boolean) As Boolean _
                                      Implements ISessionIDManager.InitializeRequest

      If pConfig.Cookieless = HttpCookieMode.UseCookies Then
        supportSessionIDReissue = False
        Return False
      Else
        supportSessionIDReissue = True
        Return context.Response.IsRequestBeingRedirected
      End If
    End Function



    '
    ' ISessionIDManager Members
    '


    '
    ' ISessionIDManager.GetSessionID
    '
    Public Function GetSessionID(context As HttpContext) As String _
      Implements ISessionIDManager.GetSessionID
    
      Dim id As String = Nothing

      If pConfig.Cookieless = HttpCookieMode.UseUri Then
        ' Retrieve the SessionID from the URI.
      Else
        id = context.Request.Cookies(pConfig.CookieName).Value
      End If    

      ' Verify that the retrieved SessionID is valid. If not, return Nothing.

      If Not Validate(id) Then _
        id = Nothing

      Return id
    End Function

    '
    ' ISessionIDManager.CreateSessionID
    '

    Public Function CreateSessionID(context As HttpContext) As String _
      Implements ISessionIDManager.CreateSessionID
    
      Return Guid.NewGuid().ToString()
    End Function

    '
    ' ISessionIDManager.RemoveSessionID
    '

    Public Sub RemoveSessionID(context As HttpContext) _
      Implements ISessionIDManager.RemoveSessionID

      context.Response.Cookies.Remove(pConfig.CookieName)

    End Sub


    '
    ' ISessionIDManager.SaveSessionID
    '

    Public Sub SaveSessionID(context As HttpContext, _
                             id As String, _
                             ByRef redirected As Boolean, _
                             ByRef cookieAdded As Boolean) _
      Implements ISessionIDManager.SaveSessionID
    
      redirected = False
      cookieAdded = False

      If pConfig.Cookieless = HttpCookieMode.UseUri Then

        ' Add the SessionID to the URI. Set the redirected variable as appropriate.

        redirected = True
        Return
      Else
        context.Response.Cookies.Add(New HttpCookie(pConfig.CookieName, id))
        cookieAdded = True
      End If
    End Sub


    '
    ' ISessionIDManager.Validate
    '

    Public Function Validate(id As String) As Boolean _
      Implements ISessionIDManager.Validate
    
      Try
        Dim testGuid As Guid = New Guid(id)

        If id = testGuid.ToString() Then _
          Return True
      Catch
      
      End Try

      Return False
    End Function

  End Class
End Namespace

Comentários

A ISessionIDManager interface identifica os métodos que você deve implementar para criar um gerenciador personalizado para valores de identificador de sessão.The ISessionIDManager interface identifies the methods that you must implement to create a custom manager for session-identifier values. Uma ISessionIDManager implementação de interface cria e valida valores de identificador de sessão e gerencia o armazenamento de um identificador de sessão na resposta http, bem como a recuperação de um valor de identificador de sessão da solicitação HTTP.An ISessionIDManager interface implementation creates and validates session-identifier values, and manages the storage of a session identifier in the HTTP response as well as the retrieval of a session-identifier value from the HTTP request. Você habilita o Gerenciador de ID de sessão personalizado usando o sessionIDManagerType atributo do elemento de configuração do elemento sessionState (esquema de configurações ASP.net) .You enable the custom session-ID manager using the sessionIDManagerType attribute of the sessionState Element (ASP.NET Settings Schema) configuration element.

Se a ISessionIDManager implementação da interface oferecer suporte a identificadores de sessão sem cookie, você precisará implementar uma solução para enviar e recuperar identificadores de sessão na URL, como um filtro ISAPI.If your ISessionIDManager interface implementation will support cookieless session identifiers, you will need to implement a solution for sending and retrieving session identifiers in the URL, such as an ISAPI filter.

Se você quiser fornecer valores de identificador de sessão personalizados a serem usados pelo estado de sessão ASP.NET, poderá criar uma classe que herde a SessionIDManager classe e substituir somente os CreateSessionID Validate métodos e por sua própria implementação personalizada.If you only want to supply custom session-identifier values to be used by ASP.NET session state, you can create a class that inherits the SessionIDManager class and override only the CreateSessionID and Validate methods with your own custom implementation. Isso permite que você forneça seus próprios valores de identificador de sessão, enquanto dependem da classe base SessionIDManager para armazenar valores na resposta http e recuperar valores da solicitação HTTP.This enables you to supply your own session-identifier values, while relying on the base SessionIDManager class to store values to the HTTP response and retrieve values from the HTTP request. Para obter um exemplo de como substituir a SessionIDManager classe e implementar esses métodos, consulte o exemplo fornecido para o CreateSessionID método da SessionIDManager classe.For an example of overriding the SessionIDManager class and implementing these methods, see the example provided for the CreateSessionID method of the SessionIDManager class.

Métodos

CreateSessionID(HttpContext)

Cria um identificador de sessão exclusivo.Creates a unique session identifier.

GetSessionID(HttpContext)

Obtém o identificador de sessão do contexto da solicitação HTTP atual.Gets the session identifier from the context of the current HTTP request.

Initialize()

Inicializa o objeto SessionIDManager.Initializes the SessionIDManager object.

InitializeRequest(HttpContext, Boolean, Boolean)

Realiza a inicialização do objeto SessionIDManager segundo a solicitação.Performs per-request initialization of the SessionIDManager object.

RemoveSessionID(HttpContext)

Exclui o identificador de sessão do cookie ou da URL.Deletes the session identifier from the cookie or from the URL.

SaveSessionID(HttpContext, String, Boolean, Boolean)

Salva um identificador de sessão recém-criado para a resposta HTTP.Saves a newly created session identifier to the HTTP response.

Validate(String)

Confirma que o identificador de sessão fornecido é válido.Confirms that the supplied session identifier is valid.

Aplica-se a