/// <summary> /// Ensures a specific key to be either already in the ASP.NET MVC session state or to be newly created /// </summary> /// <typeparam name = "T">The generic type to be returned</typeparam> /// <param name = "state">The session state.</param> /// <param name = "key">The session state key.</param> /// <returns>The session state value.</returns> /// <example> /// <code> /// public List<string> StringValues { /// get { return this.Session.Ensure<List<string>>("StringValues"); } /// set { this.ViewState.Set("StringValues", value); } /// } /// </code> /// </example> /// <remarks> /// Contributed by Michael T, http://about.me/MichaelTran /// </remarks> public static T Ensure <T>(this HttpSessionStateBase state, string key) where T : class, new() { var value = state.Get <T>(key); if (value == null) { value = new T(); state.Set(key, value); } return(value); }
/// <summary> /// 从Redis取Session /// </summary> /// <typeparam name="T"></typeparam> /// <param name="_"></param> /// <param name="key">键</param> /// <param name="expire">过期时间,默认20分钟</param> /// <returns></returns> public static T GetByRedis <T>(this HttpSessionStateBase _, string key, int expire = 20) where T : class { if (HttpContext.Current is null) { throw new Exception("请确保此方法调用是在同步线程中执行!"); } var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value; if (!string.IsNullOrEmpty(sessionKey)) { T obj = default(T); if (_ != default(T)) { obj = _.Get <T>(key); } if (obj == null) { try { sessionKey = "Session:" + sessionKey; using (RedisHelper redisHelper = RedisHelper.GetInstance(1)) { if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key)) { redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire)); return(redisHelper.GetHash <T>(sessionKey, key)); } return(default(T)); } } catch { return(default(T)); } } return(obj); } return(default(T)); }
public static string GetRoleText(this HttpSessionStateBase state) { return(state.Get <string>(KEY_ROLE_TEXT)); }
public static int[] GetRoleIds(this HttpSessionStateBase state) { return(state.Get <int[]>(KEY_ROLEID_LIST)); }
public static UserDetails GetUserDetail(this HttpSessionStateBase state) { return(state.Get <UserDetails>(KEY_USER_DETAIL)); }
public static string GetUserName(this HttpSessionStateBase state) { return(state.Get <string>(KEY_USER_NAME)); }
public static int?GetUserId(this HttpSessionStateBase state) { return(state.Get <int?>(KEY_USER_ID)); }
public static ResponseLogin GetCurrentUser(this HttpSessionStateBase Session) { var user = (ResponseLogin)Session.Get(GlobalKey.CurrentUser); return(user); }