我希望在我的应用程序的单独进程中拥有会话状态,但我也希望在用户会话结束时运行一些代码。(更改指示他们是否在线的状态字符串并减少在线用户数。)
如果我的会话状态是 Web 配置中的 InProc,我可以使用 Session_End 方法运行此代码,但如果不是,我该怎么做?
我希望在我的应用程序的单独进程中拥有会话状态,但我也希望在用户会话结束时运行一些代码。(更改指示他们是否在线的状态字符串并减少在线用户数。)
如果我的会话状态是 Web 配置中的 InProc,我可以使用 Session_End 方法运行此代码,但如果不是,我该怎么做?
您不能分配在会话结束时始终运行的事件处理程序。有一些近似值,例如将事件处理程序分配给 InProc 会话的 End 事件(仅当会话正常结束时才会运行),或更改 SQL Server 会话的 DeleteExpiredSessions proc。
您使用的是 SQL 状态还是使用 IIS 状态服务器服务?
如果您使用的是 SQL 状态,则只需检查用户 ID。当会话超时时,该行被删除,就是这样。
如果您使用的是 IIS 状态服务器服务,则没有直接的方法可以在 Session_End 或类似的东西上执行代码。对不起。
在尝试检测会话何时过期时,存在一些不确定性原则。通过查询服务器以查看它是否处于活动状态(使用 AJAX 或类似方法),您实际上是在保持它处于活动状态,这通常是您想要的完全相反的行为。
我通常通过在页面中嵌入 javascript 代码来做到这一点。:
var sessionTimeout = 20; //minutes - set this programmatically server-side based on your configured timout interval
setTimeout('timeoutAlert()', (sessionTimeout + 1) * 1000 * 60); //we add one minute buffer because this is an inaccurate process and we want to make sure they are actually timed out before we attempt to redirect
function timeoutAlert()
{
alert("Your sesssion has ended, you will now be redirect to the login page.");
document.location = '/home.aspx';
}
注意这个 timeoutAlert() 可以修改一些 HTML 客户端,运行一些 AJAX 来执行代码服务器端,无论你需要它做什么。如果您在页面呈现后对服务器进行任何调用(例如,通过 AJAX),则必须小心取消和重置 setTimeout。
If you are using SQL Server, Then you could modify the DeleteExpiredSessions stored procedure to do your work (i.e. decrement online users).
alternatively, you can check a session variable on each page load, if it comes back null then the session has ended.
You can also put a javascript check to see if the browser has closed or, if the logout button has been clicked, etc... then make an ajax call to manually close the session.