SessionStateUtility.AddHttpSessionStateToContext(HttpContext, IHttpSessionState) Método
Definição
Aplica os dados da sessão ao contexto da solicitação atual.Applies the session data to the context for the current request.
public:
static void AddHttpSessionStateToContext(System::Web::HttpContext ^ context, System::Web::SessionState::IHttpSessionState ^ container);
public static void AddHttpSessionStateToContext (System.Web.HttpContext context, System.Web.SessionState.IHttpSessionState container);
static member AddHttpSessionStateToContext : System.Web.HttpContext * System.Web.SessionState.IHttpSessionState -> unit
Public Shared Sub AddHttpSessionStateToContext (context As HttpContext, container As IHttpSessionState)
Parâmetros
- context
- HttpContext
O objeto HttpContext ao qual adicionar o objeto HttpSessionState.The HttpContext object to which to add the HttpSessionState object.
- container
- IHttpSessionState
A instância de implementação IHttpSessionState a adicionar ao contexto HTTP especificado.The IHttpSessionState implementation instance to add to the specified HTTP context.
Exceções
Um objeto HttpSessionState para a sessão atual já foi adicionado ao context especificado.An HttpSessionState object for the current session has already been added to the specified context.
Exemplos
O exemplo de código a seguir mostra o manipulador para o AcquireRequestState evento em um módulo de estado de sessão personalizado.The following code example shows the handler for the AcquireRequestState event in a custom session-state module. O módulo personalizado recupera informações de sessão existentes ou cria novas informações de sessão e usa o AddHttpSessionStateToContext método para adicioná-la ao HttpContext da solicitação atual.The custom module retrieves existing session information or creates new session information and uses the AddHttpSessionStateToContext method to add it to the HttpContext of the current request. Este exemplo de código faz parte de um exemplo maior fornecido para a SessionStateUtility classe.This code example is part of a larger example provided for the SessionStateUtility class.
//
// Event handler for HttpApplication.AcquireRequestState
//
private void OnAcquireRequestState(object source, EventArgs args)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
bool isNew = false;
string sessionID;
SessionItem sessionData = null;
bool supportSessionIDReissue = true;
pSessionIDManager.InitializeRequest(context, false, out supportSessionIDReissue);
sessionID = pSessionIDManager.GetSessionID(context);
if (sessionID != null)
{
try
{
pHashtableLock.AcquireReaderLock(Int32.MaxValue);
sessionData = (SessionItem)pSessionItems[sessionID];
if (sessionData != null)
sessionData.Expires = DateTime.Now.AddMinutes(pTimeout);
}
finally
{
pHashtableLock.ReleaseReaderLock();
}
}
else
{
bool redirected, cookieAdded;
sessionID = pSessionIDManager.CreateSessionID(context);
pSessionIDManager.SaveSessionID(context, sessionID, out redirected, out cookieAdded);
if (redirected)
return;
}
if (sessionData == null)
{
// Identify the session as a new session state instance. Create a new SessionItem
// and add it to the local Hashtable.
isNew = true;
sessionData = new SessionItem();
sessionData.Items = new SessionStateItemCollection();
sessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(context);
sessionData.Expires = DateTime.Now.AddMinutes(pTimeout);
try
{
pHashtableLock.AcquireWriterLock(Int32.MaxValue);
pSessionItems[sessionID] = sessionData;
}
finally
{
pHashtableLock.ReleaseWriterLock();
}
}
// Add the session data to the current HttpContext.
SessionStateUtility.AddHttpSessionStateToContext(context,
new HttpSessionStateContainer(sessionID,
sessionData.Items,
sessionData.StaticObjects,
pTimeout,
isNew,
pCookieMode,
SessionStateMode.Custom,
false));
// Execute the Session_OnStart event for a new session.
if (isNew && Start != null)
{
Start(this, EventArgs.Empty);
}
}
//
// Event for Session_OnStart event in the Global.asax file.
//
public event EventHandler Start;
'
' Event handler for HttpApplication.AcquireRequestState
'
Private Sub OnAcquireRequestState(ByVal [source] As Object, ByVal args As EventArgs)
Dim app As HttpApplication = CType([source], HttpApplication)
Dim context As HttpContext = app.Context
Dim isNew As Boolean = False
Dim sessionID As String
Dim sessionData As SessionItem = Nothing
Dim supportSessionIDReissue As Boolean = True
pSessionIDManager.InitializeRequest(context, False, supportSessionIDReissue)
sessionID = pSessionIDManager.GetSessionID(context)
If Not (sessionID Is Nothing) Then
Try
pHashtableLock.AcquireReaderLock(Int32.MaxValue)
sessionData = CType(pSessionItems(sessionID), SessionItem)
If Not (sessionData Is Nothing) Then
sessionData.Expires = DateTime.Now.AddMinutes(pTimeout)
End If
Finally
pHashtableLock.ReleaseReaderLock()
End Try
Else
Dim redirected, cookieAdded As Boolean
sessionID = pSessionIDManager.CreateSessionID(context)
pSessionIDManager.SaveSessionID(context, sessionID, redirected, cookieAdded)
If redirected Then Return
End If
If sessionData Is Nothing Then
' Identify the session as a new session state instance. Create a new SessionItem
' and add it to the local Hashtable.
isNew = True
sessionData = New SessionItem()
sessionData.Items = New SessionStateItemCollection()
sessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(context)
sessionData.Expires = DateTime.Now.AddMinutes(pTimeout)
Try
pHashtableLock.AcquireWriterLock(Int32.MaxValue)
pSessionItems(sessionID) = sessionData
Finally
pHashtableLock.ReleaseWriterLock()
End Try
End If
' Add the session data to the current HttpContext.
SessionStateUtility.AddHttpSessionStateToContext(context, _
New HttpSessionStateContainer(sessionID, _
sessionData.Items, _
sessionData.StaticObjects, _
pTimeout, _
isNew, _
pCookieMode, _
SessionStateMode.Custom, _
False))
' Execute the Session_OnStart event for a new session.
If isNew Then RaiseEvent Start(Me, EventArgs.Empty)
End Sub
'
' Event for Session_OnStart event in the Global.asax file.
'
Public Event Start As EventHandler
Comentários
O AddHttpSessionStateToContext método é usado por um módulo de estado de sessão para aplicar dados de sessão à solicitação atual.The AddHttpSessionStateToContext method is used by a session-state module to apply session data to the current request. Isso ocorre durante o AcquireRequestState evento no início de uma solicitação.This occurs during the AcquireRequestState event at the beginning of a request. Os dados da sessão para a solicitação atual são recuperados para uma sessão existente ou criados para uma nova sessão.Session data for the current request is either retrieved for an existing session or created for a new session. Os dados da sessão são encapsulados em uma IHttpSessionState instância de implementação, que é passada para o AddHttpSessionStateToContext método junto com o atual HttpContext .The session data is then encapsulated in an IHttpSessionState implementation instance, which is passed to the AddHttpSessionStateToContext method along with the current HttpContext. Os dados de sessão fornecidos são então disponibilizados para o código do aplicativo por meio da Session Propriedade do contexto atual.The supplied session data is then made available to application code through the Session property of the current context.