Access Membership User On Session End

梦想的初衷 提交于 2019-12-01 22:26:44

问题


I'm currently trying to write a little bit of code to do some tidying up once a user abandons their session (either via time out or logging out) however would like to access the User object so I know who the session belongs to.

Unfortunately HttpContext is null so I can't access HttpContext.User or HttpContext.User.IsInRole or even the auth cookie directly. I understand the reasons behind this but wonder if there is there any other way to get access to this information when a session times out?

That is apart from the obvious answer of duplicating some of the information in the session.

Thanks.


回答1:


You can use Global.asax's Session_End event. Session_End event is called automatically when a Session expired.

The problem is Session_End event is called without a current request. As the result, HttpContext.Current is null inside Session_End.

If you want to get user's information, you will need to save them inside Session as soon as user successfully logins.

private void Session_End(object sender, EventArgs e)
{
    // Code that runs when a session ends. 
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set 
    // to StateServer or SQLServer, the event is not raised.

    var userName = Session["UserName"];
    var sessionId = Session.SessionID;
}




回答2:


There is nothing that ties the membership user to the session.

When a user manually logs out, before your clear their session, you can get their user information.

However, if the user leaves the browser open and the session times out on the server, you will not know who that user is, so won't be able to tidy up for them.

On the server, you might need to keep track of when the user last interacted and then run a job to tidy up for users that haven't interacted in a while and are considered logged out.



来源:https://stackoverflow.com/questions/20107196/access-membership-user-on-session-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!