Allow only a single login session per user

2019-08-06 04:50发布

问题:

Essentially I am asking this question here, but I am using ASP Identity instead of the ASP.Net Membership provider, and with that, that answer is of no use to me.

回答1:

Figured out how to do it. On login I call this:

var key = user.UserName;
var timeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert(key, Session.SessionID, null, DateTime.MaxValue, timeOut, CacheItemPriority.NotRemovable, null);

And this in the Global.asax

if (Session["username"] != null)
    {
        var cacheKey = Session["username"].ToString();
        if ((string) HttpContext.Current.Cache[cacheKey] != Session.SessionID) LogOut();
    }