asp.net's next account does not allow multiple users to be online at the same time
- 2020-05-10 18:00:10
- OfStack
Method 1:
string sKey = username.Text.ToString().Trim(); // get Cache In a given Key The value of the
string sUser = Convert.ToString(Cache[sKey]); // Check for presence
if (sUser == null || sUser == String.Empty)
{
TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);// achieve Session Expiration time
HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);// The value in the cache Convenient for single sign-on
// A successful login
}
else if (Cache[sKey].ToString() == sKey)// If the account is already logged in
{
ClientScript.RegisterStartupScript(GetType(), " prompt ", "<script>alert(' I'm sorry , The current user is logged in ');</script>");
return;
}
else
{
Session.Abandon();// The main purpose of this section is to avoid unnecessary errors that may cause you to fail to log in
}
// Clear when closing the browser or window Cache The method of . In the main page aspx Add to file 1 a onunload The event . through ajax empty hOnline In the Session.SessionID
window.onunload=function(){
$.ajax({
type: "POST",
data:"sKey="+sKey;
url: "online.aspx"
});
}
online. aspx. cs code
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.Cache.Remove(sKey);
}
// in Global.asax In the file Session_End Add to the method
//Session After expired . empty hOnline In the Session.SessionID
Hashtable hOnline = (Hashtable)Application["Online"];
if (hOnline[Session.SessionID] != null)
{
hOnline.Remove(Session.SessionID);
Application.Lock();
Application["Online"] = hOnline;
Application.UnLock();
}
Method 2:
//sKey Is the login user name
if(ApplicationOnline(username.Text.tirm())){
Hashtable hOnline = new Hashtable();
hOnline[Session.SessionID] = sKey;
Application.Lock();
Application["Online"] = hOnline;
Application.UnLock();
}
public Boolean ApplicationOnline(string sKey)
{
Boolean flag = true;
Hashtable hOnline = (Hashtable)Application["Online"];
if (hOnline != null)
{
IDictionaryEnumerator idE = hOnline.GetEnumerator();
while (idE.MoveNext())
{
//if (idE.Key != null && idE.Key.ToString().Equals(Session.SessionID))
//{
if (idE.Value != null && sKey.Equals(idE.Value.ToString()))
{
flag = false;
}
break;
//}
}
}
return flag;
}
// Clear when closing the browser or window Session.SessionID The method of . In the main page aspx Add to file 1 a onunload The event . through ajax empty Session.SessionID
window.onunload=function(){
$.ajax({
type: "POST",
url: "online.aspx"
});
}
online. aspx. cs code
protected void Page_Load(object sender, EventArgs e)
{
Hashtable hOnline = (Hashtable)Application["Online"];
if (hOnline[Session.SessionID] != null)
{
hOnline.Remove(Session.SessionID);
Application.Lock();
Application["Online"] = hOnline;
Application.UnLock();
}
}