Last active
December 18, 2018 05:33
-
-
Save jingyulong/62bb07edf4ac164c0452fac091acbd6f to your computer and use it in GitHub Desktop.
Unique Login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class OnlineInfo | |
{ | |
private static readonly string CurrentSessionId = HttpContext.Current.Session.SessionID; | |
public static string CurrentUserName { get; set; } | |
/// <summary> | |
/// Key:SessionID,Value:UserName | |
/// </summary> | |
public static Dictionary<string, string> List | |
{ | |
get => (Dictionary<string, string>)HttpContext.Current.Application["Online"] ?? | |
new Dictionary<string, string>(); | |
set | |
{ | |
HttpContext.Current.Application.Lock(); | |
HttpContext.Current.Application["Online"] = value; | |
HttpContext.Current.Application.UnLock(); | |
} | |
} | |
public static bool IsOnline => List.ContainsKey(CurrentSessionId) && List[CurrentSessionId] != "OffLine"; | |
public static bool HasKey => List.ContainsKey(CurrentSessionId); | |
public static bool HasUser => List.ContainsValue(CurrentUserName); | |
public static void Login() | |
{ | |
var token = Authentication.GetToken(CurrentUserName); | |
HttpContext.Current.Session[HttpContext.Current.Session.SessionID] = token; | |
if (HasUser) | |
{ | |
var previousUserSessionKey = List.First(d => d.Value == CurrentUserName).Key; | |
List[previousUserSessionKey] = "OffLine"; | |
} | |
if (!HasKey) | |
{ | |
List.Add(CurrentSessionId, CurrentUserName); | |
} | |
} | |
public static void CheckIsOnline() | |
{ | |
if (!IsOnline) | |
{ | |
Logout(); | |
} | |
} | |
public static void Logout() | |
{ | |
HttpContext.Current.Session[CurrentSessionId] = null; | |
List.Remove(CurrentSessionId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment