【发布时间】:2010-10-07 16:18:22
【问题描述】:
在我的 asp.net 网站中,我在用户登录时创建了一个会话,我想在此会话到期之前在数据库中执行一些操作。我在确定应该在哪里编写代码以及如何编写代码时遇到问题知道会话即将到期。
我不确定“Global.asax”的“session_end”事件是否符合我的要求,因为我要检查的会话是手动创建的(不是浏览器实例)。
有人能给我指明正确的方向吗?
谢谢。
【问题讨论】:
在我的 asp.net 网站中,我在用户登录时创建了一个会话,我想在此会话到期之前在数据库中执行一些操作。我在确定应该在哪里编写代码以及如何编写代码时遇到问题知道会话即将到期。
我不确定“Global.asax”的“session_end”事件是否符合我的要求,因为我要检查的会话是手动创建的(不是浏览器实例)。
有人能给我指明正确的方向吗?
谢谢。
【问题讨论】:
这可能非常棘手,因为只有在 Session 模式设置为 InProc 时才支持 Session_End 方法。您可以做的是使用 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);
}
然后,当 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());
}
【讨论】: