如何在asp.net会话变量到期之前执行服务器端代码?

在我的asp.net网站上,我在用户登录时创建一个会话,我想在此会话到期之前在数据库中执行一些操作。我在确定应该在哪里编写代码时遇到问题以及如何知道会话即将到期。

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

有人可以请我指出正确的方向吗?

谢谢。

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

使用Munsifali的技术,您可以:

   

然后在应用程序启动时连接模块:

 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); } 

然后,当Session启动时,您可以输入一些用户数据:

 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()); }