问题
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