如何在cookie中存储对象

本文关键字:存储 对象 cookie | 更新日期: 2023-09-27 18:01:35

虽然这在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中,然后再进行验证。

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

如何在cookie中存储对象

cookie只是字符串数据;要做到这一点的唯一方法是将其序列化为字符串(xml, json, base-64任意二进制,无论什么),然而,如果它与安全信息("我是谁?")相关,您不应该真的信任cookie中的任何内容,因为a:最终用户很容易更改它,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);

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

你可以序列化你的对象成字符串或JSON如果你真的想。建议尽可能保持数据的轻便性。请记住:每次我们从浏览器到服务器通信时,你每次都传递了所有的数据。

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

权衡:增加网络流量(cookie来回传递)Vs更大的服务器端内存占用和/或辅助存储。

顺便说一句:别忘了,如果你真的需要的话,二进制也可以被编码成文本。

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

试试这样做?

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

在cookie中可以存储字符串类型的值。您可以将对象存储到会话、视图状态或缓存中。但仍然希望存储在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中保存一个小的"Buy"对象(保存/延长/重置/清除)。而不是单独的代码行,我已经使用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<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";
}

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