I want to implement a code that enables only one session per user. I use asp.net with forms authentication .

I read this post: Limit only one session per user in ASP.NET

but I want to do the opposite, to disconnect all previous sessions.

here is my code:

void Application_Start(object sender, EventArgs e) 
{
    Application["UsersLoggedIn"] = new System.Collections.Generic.Dictionary<string, string>(); }

when user logs in, I insert a record : username, sessionID. if the username exists, I just update the sessionID

    void Application_BeginRequest(object sender, EventArgs e)
    {
        System.Collections.Generic.Dictionary<string, string> d = HttpContext.Current.Application["UsersLoggedIn"] as System.Collections.Generic.Dictionary<string, string>;
        if (d != null)
        {
            if (d.Count > 0)
            {
                    string userName = HttpContext.Current.User.Identity.Name;
                    if (!string.IsNullOrEmpty(userName))
                    {
                        if (d.ContainsKey(userName))
                        {
                            if (d[userName] != HttpContext.Current.Session.SessionID)
                            {
                                FormsAuthentication.SignOut();
                                Session.Abandon();
                            }
                        }
                    }
}
}

but I get empty HttpContext.Current.User. I tried also "AuthenticatedRequest", but then I get null Session.

any idea please?

有帮助吗?

解决方案

If you want to access HttpContext.Current.User and Session, you should use the AcquireRequestState event.

其他提示

If you're in a load balanced situation with multiple servers at place you'll want to persist this in some way, the problem comes when you need to release the user lock (either on termination of the users session or logout).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top