开发者

How to subscribe for SessionStateItemExpireCallback in asp.net mvc

开发者 https://www.devze.com 2023-02-16 21:23 出处:网络
I searched a lot about this but couldn\'t find any particular examp开发者_C百科le of real usage. MSDN says a lot about implementing custom session state provider but I don\'t wanna do that. Could anyo

I searched a lot about this but couldn't find any particular examp开发者_C百科le of real usage. MSDN says a lot about implementing custom session state provider but I don't wanna do that. Could anyone advise how can I perform some actions when session expires

Usecase: Session timeout 10 minutes. User opens a page and session is created application marks user in database as logged in. One minute after page open user closes browser so in 9 minutes session will expire and app should execute some code to mark user as offline.

Thanks in advance!


You could try subscribing for the Session_End event in Global.asax:

protected void Session_End()
{
    ...
    // Remark: don't use Context here, it will be null as the
    // user might have closed his browser long ago => no request/response
    // You could get the corresponding Session.SessionID though
}

You should note that this event is only triggered if you are using a InProc session. With SqlServer and StateServer modes this event is never called simply because in the implementation of their corresponding session state providers the SetItemExpireCallback method simply return false. Quoting:

How do the built-in session state providers handle expiration callbacks? The in-process session state provider, InProcSessionStateStore, stores session content in the ASP.NET application cache and takes advantage of the cache's sliding-expiration feature to expire sessions when they go for a specified period of time without being accessed. When the provider is notified via a cache removal callback that a session expired from the cache, it notifies SessionStateModule, and SessionStateModule fires a Session_End event. The other two built-in providers—OutOfProcSessionStateStore and SqlSessionStateStore—don't support expiration callbacks. Both return false from SetItemExpireCallback. OutOfProcSessionStateStore uses the application cache to store sessions, but since session data is stored in a remote process (the "state server" process), the provider doesn't attempt to notify SessionStateModule when a session expires. SqlSessionStateStore relies on a SQL Server agent to "scavenge" the session state database and clean up expired sessions. Having the agent notify the provider about expired sessions so the provider could, in turn, notify SessionStateModule would be a tricky endeavor indeed-especially in a Web farm.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号