How to store an object in a cookie?

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

    Try something like this?

    StringWriter outStream = new StringWriter();
    XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
    s.Serialize(outStream, myObj);
    cookie.Value = outStream.ToString();
    
    0 讨论(0)
  • 2020-12-15 09:15

    The short answer is: Cookies store strings, and not binary objects.

    You could serialize your object into strings or JSON if you really wanted to. Suggest keeping the data back/forth as lightweight as you can. Remember: each time we communicate from the browser to the server, you're passing all that data each time.

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

    to store an object in a cookie we have to convert it into stringified presentation (compressed or not) which is limited to 4kb. this example demonstrates how to keep a little "Buy" object in a cookies (save/prolong/reset/clear). instead of separate code lines i've used a Json to fill this object with some data.

    using System;
    using System.Collections.Generic;
    using System.Web;
    using Newtonsoft.Json;
    public class Customer
    {
        public int id;
        public string name;
    }
    public class Order
    {
        public int id;
        public decimal total;
        public Customer customer;
    }
    public class OrderItem
    {
        public int id;
        public string name;
        public decimal price;
    }
    public class Buy
    {
        public Order order;
        public List<OrderItem> cart;
    }
    static readonly string cookieName = @"buy";
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!IsPostBack)
            Restore_Click(null, null);
    }
    protected void Save_Click(object sender, EventArgs e)
    {
        string buy = JsonConvert.SerializeObject(new
        {
            order = new
            {
                id = 1,
                total = 20.10,
                customer = new
                {
                    id = 1,
                    name = "Stackoverflow"
                }
            },
            cart = new[] {
                new {
                    id = 1 , 
                    name = "Stack",
                    price = 10.05 
                },
                new {
                    id = 2 , 
                    name = "Overflow",
                    price = 10.05 
                }
            }
        });
        HttpContext.Current.Response.Cookies.Add(
            new HttpCookie(cookieName, buy) {
                Expires = DateTime.Now.AddDays(7)
            }
        );
        StatusLabel.Text = "Saved";
    }
    protected void Prolong_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
        if (cookie != null)
        {
            cookie.Expires = DateTime.Now.AddDays(7);
            HttpContext.Current.Response.Cookies.Add(cookie);
            StatusLabel.Text = "Prolonged";
        }
        else StatusLabel.Text = "Not prolonged - expired";
    }
    protected void Restore_Click(object sender, EventArgs e)
    {
        Buy buy = null;
        HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
        if (cookie != null)
        {
            buy = JsonConvert.DeserializeObject<Buy>(cookie.Value);
            StatusLabel.Text = "Restored";
        }
        else StatusLabel.Text = "Not restored - expired";
    }
    protected void ClearOut_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
        if (cookie != null)
        {
            cookie.Expires = DateTime.Now.AddMonths(-1);
            HttpContext.Current.Response.Cookies.Add(cookie);
            StatusLabel.Text = "Cleared out";
        }
        else StatusLabel.Text = "Not found - expired";
    }
    
    0 讨论(0)
  • 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;
            }
    
        }
    
    0 讨论(0)
  • 2020-12-15 09:26

    you could encrypt such a cookie as well. The contents (json/xml/etc) would be a bit safer then. Server-side caching as Marc suggests is probably better.

    Tradeoff: increased traffic on the wire (cookies are passed back and forth) Vs larger server-side memory footprint and / or secondardy storage.

    btw: don't forget that binary can be encoded to text if you really need that.

    http://www.codeproject.com/KB/security/TextCoDec.aspx

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

    you can try this:

    public void AddToCookie(SessionUser sessionUser)
        {
            var httpCookie = HttpContext.Current.Response.Cookies["SessionUser"];
            if (httpCookie != null)
            {
                httpCookie["ID"] = sessionUser.ID.ToString();
                httpCookie["Name"] = sessionUser.Name;
                httpCookie["Email"] = sessionUser.Email;
                httpCookie["Phone"] = sessionUser.Phone;
                httpCookie.Expires = DateTime.Now.AddDays(1);
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题