How to store an object in a cookie?

后端 未结 10 1571
名媛妹妹
名媛妹妹 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:33

    in cookie you can store a value of type string. you can store your object into session,viewstate or in cache. but still want to store in cookies, just use system.web.script.javascriptserialization class and convert the whole object in json string and then store that on your cookie.

    0 讨论(0)
  • 2020-12-15 09:38

    A cookie is just string data; the only way to do that would be to serialize it as a string (xml, json, base-64 of arbitrary binary, whatever), however, you shouldn't really trust anything in a cookie if it relates to security information ("who am I?") as a: it is easy for the end-user to change it, and b: you don't want the overhead of anything biggish on every single request.

    IMO, caching this as the server is the correct thing; don't put this in a cookie.

    0 讨论(0)
  • 2020-12-15 09:38
    System.Collections.Specialized.NameValueCollection cookiecoll = new System.Collections.Specialized.NameValueCollection();
    
                cookiecoll.Add(bizID.ToString(), rate.ToString());
    
    
            HttpCookie cookielist = new HttpCookie("MyListOfCookies");
            cookielist.Values.Add(cookiecoll);
            HttpContext.Current.Response.Cookies.Add(cookielist);
    
    0 讨论(0)
  • 2020-12-15 09:40

    You can use JSON

    string myObjectJson = new JavaScriptSerializer().Serialize(myObject);
    var cookie = new HttpCookie("myObjectKey", myObjectJson) 
    {     
        Expires = DateTime.Now.AddYears(1) 
    };
    HttpContext.Response.Cookies.Add(cookie);
    
    0 讨论(0)
提交回复
热议问题