aspnetcore之session

 

 
startUp中
#region AspNetCore中使用Session services.AddDistributedMemoryCache(); services.AddSession(option => { option.IdleTimeout = TimeSpan.FromMinutes(3); option.Cookie.Name = "MySid"; }); #endregion
app.UseSession();

 

 


Controller中

#region
AspnetCore中使用Session public IActionResult About() { var UserInfo = "我的NetCore之Session"; HttpContext.Session.Set("SessionKey", System.Text.Encoding.UTF8.GetBytes(UserInfo)); return View(); } public IActionResult Contact() { var userInfo = string.Empty; if (HttpContext.Session.TryGetValue("SessionKey", out var bt)) { userInfo = System.Text.Encoding.UTF8.GetString(bt); } ViewData["Message"] = string.IsNullOrWhiteSpace(userInfo) ? "Session获取为空" : userInfo; return View(); } #endregion

 

接下来如果直接进入Contact页面时会获取不到session:

 

 

先运行About获取到session,再运行Contact时,获取到session

 

 

 

另一种扩展方法

public static class PublicExtensions
     {
         #region ISession扩展
 
         /// <summary>
         /// 设置session
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <param name="session"></param>
         /// <param name="key"></param>
         /// <param name="val"></param>
         /// <returns></returns>
         public static bool Set<T>(this ISession session, string key, T val)
         {
             if (string.IsNullOrWhiteSpace(key) || val == null) { return false; }
 
             var strVal = JsonConvert.SerializeObject(val);
             var bb = Encoding.UTF8.GetBytes(strVal);
             session.Set(key, bb);
             return true;
         }
 
         /// <summary>
         /// 获取session
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <param name="session"></param>
         /// <param name="key"></param>
         /// <returns></returns>
         public static T Get<T>(this ISession session, string key)
         {
             var t = default(T);
             if (string.IsNullOrWhiteSpace(key)) { return t; }
 
             if (session.TryGetValue(key, out byte[] val))
             {
                 var strVal = Encoding.UTF8.GetString(val);
                 t = JsonConvert.DeserializeObject<T>(strVal);
             }
             return t;
         }
 
         #endregion
     }

public class MoUser { public string UserName { get; set; } public string Password { get; set; } }
 #region  AspnetCore中使用Session

        public IActionResult About()
        {
            MoUser user = new MoUser();

            user.UserName = "你好";
            user.Password = "hello";

            HttpContext.Session.Set<MoUser>("nihao", user);

            return View();
        }
        public IActionResult Contact()
        {
            var user = HttpContext.Session.Get<MoUser>("nihao");
            ViewData["Message"] = user == null ? "Session获取为空" : $"昵称:{user.UserName},密码:{user.Password}";

            return View();
        }
        #endregion

 

posted @ 2018-10-09 14:30  NICETOMEETYOUSEVEN  阅读(329)  评论(0编辑  收藏  举报