How to store an object in a cookie?

后端 未结 10 1827
名媛妹妹
名媛妹妹 2020-12-15 08:49

While this is possible in C#: (User is a L2S class in this instance)

User user = // function to get user
Session[\"User\"] = user;

why this

10条回答
  •  臣服心动
    2020-12-15 09:22

    Cookie store only strings. What you can do:

     var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     var json = serializer.Serialize(user);
    controller.Response.SetCookie(
            new HttpCookie({string_name}, json)
            {
                Expires = false // use this when you want to delete
                        ? DateTime.Now.AddMonths(-1)
                        : DateTime.Now.Add({expiration})
            });
    

    This should insert the entire object to cookie.

    In order to read from the cookie back to an object:

        public static {Object_Name} GetUser(this Controller controller)
        {
    
            var httpRequest = controller.Request;
    
            if (httpRequest.Cookies[{cookie_name}] == null)
            {
                return null;
            }
            else
            {
                var json = httpRequest.Cookies[{cookie_name}].Value;
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var result = serializer.Deserialize<{object_name}>(json);
                return result;
            }
    
        }
    

提交回复
热议问题