如何在cookie中存储对象?

虽然这在C#中是可能的:(在这种情况下,User是一个L2S类)

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

为什么这不可能?

 User user = // function to get user HttpCookie cookie = new HttpCookie(); cookie.Value = user; 

怎么能这样呢? 我不想将用户的id存储在cookie中,然后进行一些validation。

顺便说一句,如果可能的话,将对象存储在cookie中而不仅仅是ID是安全的吗?

cookie只是字符串数据; 唯一的方法是将它序列化为一个字符串(xml,json,任意二进制的base-64,无论如何),然而,如果它与安全信息有关,你不应该真正信任cookie中的任何东西(“谁我是吗?“)作为:最终用户很容易改变它,而b:你不希望每一个请求都有任何大问题的开销。

IMO,缓存这个服务器是正确的; 不要把它放在一个cookie中。

您可以使用JSON

 string myObjectJson = new JavaScriptSerializer().Serialize(myObject); var cookie = new HttpCookie("myObjectKey", myObjectJson) { Expires = DateTime.Now.AddYears(1) }; HttpContext.Response.Cookies.Add(cookie); 

简短的回答是:Cookies存储字符串,而不是二进制对象。

如果你真的想要,可以将对象序列化为字符串或JSON。 建议尽可能轻松地保持数据的前后传输。 请记住:每次我们从浏览器与服务器进行通信时,您每次都会传递所有数据。

你也可以加密这样的cookie。 内容(json / xml / etc)会更安全一些。 Marc建议的服务器端缓存可能更好。

权衡:线路上的流量增加(cookie来回传递)与更大的服务器端内存占用和/或第二存储。

顺便说一句:如果你确实需要,可以将二进制文件编码为文本。

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

尝试这样的事情?

 StringWriter outStream = new StringWriter(); XmlSerializer s = new XmlSerializer(typeof(List>)); s.Serialize(outStream, myObj); cookie.Value = outStream.ToString(); 

在cookie中,您可以存储string类型的值。 您可以将对象存储到会话,视图状态或缓存中。 但仍想存储在cookie中,只需使用system.web.script.javascriptserialization类并将整个对象转换为json字符串,然后将其存储在cookie中。

 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); 

你可以试试这个:

 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); } } 

要将对象存储在cookie中,我们必须将其转换为字符串化的表示(压缩或不压缩),限制为4kb。 这个例子演示了如何在cookie中保留一点“购买”对象(保存/延长/重置/清除)。 而不是单独的代码行我已经使用Json用一些数据填充此对象。

 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 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(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"; } 

Cookie只存储字符串。 你可以做什么:

  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}) }); 

这应该将整个对象插入cookie。

为了从cookie读回一个对象:

  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; } }