虽然这在C#中是可行的:(在这种情况下,用户是一个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是安全的吗?
答案 0 :(得分:12)
Cookie只是字符串数据;唯一的方法是将它序列化为一个字符串(xml,json,任意二进制的base-64,无论如何),但是,你不应该真的信任cookie中的任何东西与安全信息(“我是谁?”)有关:最终用户很容易改变它,而b:你不希望每次请求都有任何大的开销。
IMO,缓存这个服务器是正确的;不要把它放在饼干里。
答案 1 :(得分:11)
您可以使用JSON
string myObjectJson = new JavaScriptSerializer().Serialize(myObject);
var cookie = new HttpCookie("myObjectKey", myObjectJson)
{
Expires = DateTime.Now.AddYears(1)
};
HttpContext.Response.Cookies.Add(cookie);
答案 2 :(得分:4)
简短的回答是:Cookies存储字符串,而不是二进制对象。
如果您真的想要,可以将对象序列化为字符串或JSON。建议尽可能轻松地保持数据的前后传输。请记住:每次我们从浏览器与服务器进行通信时,您每次都会传递所有数据。
答案 3 :(得分:1)
你也可以加密这样的cookie。内容(json / xml / etc)会更安全一些。 Marc建议的服务器端缓存可能更好。
权衡:线路上的流量增加(cookie来回传递)与更大的服务器端内存占用和/或第二次存储。
顺便说一下:如果你确实需要,可以将二进制文件编码为文本。
答案 4 :(得分:0)
尝试这样的事情?
StringWriter outStream = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
s.Serialize(outStream, myObj);
cookie.Value = outStream.ToString();
答案 5 :(得分:0)
在cookie中,您可以存储string类型的值。您可以将对象存储到会话,视图状态或缓存中。但仍想存储在cookie中,只需使用system.web.script.javascriptserialization类并将整个对象转换为json字符串,然后将其存储在cookie中。
答案 6 :(得分:0)
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);
答案 7 :(得分:0)
你可以试试这个:
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);
}
}
答案 8 :(得分:0)
将对象存储在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<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";
}
答案 9 :(得分:0)
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;
}
}