2010-10-07 66 views
2

在我的聊天室网站上,我创建了一个会话,用户登录后,我想在会话过期前在数据库中执行一些操作。我在确定应该在哪里编写代码时遇到问题,我将如何知道会议即将到期。如何在asp.net会话变量过期之前执行服务器端代码?

我不确定'Global.asax'的'session_end'事件是否符合我的要求,因为我想检查的会话是手动创建的(而不是浏览器实例)。

请问有人能让我走向正确的方向吗?

谢谢。

回答

3

这可能会非常棘手,也就是因为Session_End方法仅在Session模式设置为InProc时受支持。你可以做的是使用一个IHttpModule来监视存储在会话中的项目,并在会话过期时触发一个事件。在CodeProject上有一个例子(http://www.codeproject.com/KB/aspnet/SessionEndStatePersister.aspx),但它并非没有限制,例如它在webfarm场景中不起作用。

使用Munsifali的技术,你可以这样做:

<httpModules> 
<add name="SessionEndModule" type="SessionTestWebApp.Components.SessionEndModule, SessionTestWebApp"/> 
</httpModules> 

,然后在应用程序启动的电缆铺设工作模块:

protected void Application_Start(object sender, EventArgs e) 
{ 
    // In our sample application, we want to use the value of Session["UserEmail"] when our session ends 
    SessionEndModule.SessionObjectKey = "UserEmail"; 

    // Wire up the static 'SessionEnd' event handler 
    SessionEndModule.SessionEnd += new SessionEndEventHandler(SessionTimoutModule_SessionEnd); 
} 

private static void SessionTimoutModule_SessionEnd(object sender, SessionEndedEventArgs e) 
{ 
    Debug.WriteLine("SessionTimoutModule_SessionEnd : SessionId : " + e.SessionId); 

    // This will be the value in the session for the key specified in Application_Start 
    // In this demonstration, we've set this to 'UserEmail', so it will be the value of Session["UserEmail"] 
    object sessionObject = e.SessionObject; 

    string val = (sessionObject == null) ? "[null]" : sessionObject.ToString(); 
    Debug.WriteLine("Returned value: " + val); 
} 

然后,当会议开始时,你可以在一些用户丢数据:

protected void Session_Start(object sender, EventArgs e) 
{ 
    Debug.WriteLine("Session started: " + Session.SessionID); 

    Session["UserId"] = new Random().Next(1, 100); 
    Session["UserEmail"] = new Random().Next(100, 1000).ToString() + "@domain.com"; 

    Debug.WriteLine("UserId: " + Session["UserId"].ToString() + ", UserEmail: " + 
       Session["UserEmail"].ToString()); 
} 
相关问题