在我的 asp.net 网站中,我在用户登录时创建一个会话,我想在该会话到期之前在数据库中执行一些操作。我在确定应该在哪里编写代码以及如何知道会话时遇到问题即将过期。
我不确定“Global.asax”的“session_end”事件是否适合我的要求,因为我要检查的会话是手动创建的(不是浏览器实例)。
有人可以帮我指明正确的方向吗?
Thanks.
这可能非常棘手,因为仅当会话模式设置为 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);
}
然后,当会话启动时,您可以输入一些用户数据:
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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)