How to access the Session in ASP.NET Core via static variable?

前端 未结 3 1883
日久生厌
日久生厌 2020-12-16 20:27

In earlier version of Asp.Net session can be accessed in any page like a static variable using

System.Web.HttpContext.Current.Session[\"key\"]
3条回答
  •  庸人自扰
    2020-12-16 20:54

    If you want to store and retrieve a complex object from Session, you could instead use these extensions:

    public static class SessionExtensions
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }
    
        public static T GetObjectFromJson(this ISession session, string key)
        {
            var data = session.GetString(key);  
            if (data == null)  
            {  
                return default(T);  
            }  
            return JsonConvert.DeserializeObject(data);
        }
    }
    

    Then you would call them like this:

    User user = new User();  
    user.Name = "Jignesh Trivedi";  
    user.Percentage = 75.45;             
    
    HttpContext.Session.SetComplexData("UserData", user); 
    

    Or,

    ViewBag.data = HttpContext.Session.GetComplexData("UserData");  
    

    For details, please see https://www.c-sharpcorner.com/article/session-state-in-asp-net-core/

提交回复
热议问题