当前位置: 首页 > 编程语言 > C#

如何在cookie中存储对象?分享

时间:2023-04-11 02:45:28 C#

如何在cookie中存储对象?虽然这在C#中是可能的:(在这种情况下,User是一个L2S类)Useruser=//functiontogetuserSession["User"]=user;为什么这不可能?Useruser=//函数获取用户HttpCookiecookie=newHttpCookie();cookie.Value=用户;怎么会这样?我不想将用户的id存储在cookie中,然后进行一些身份验证。顺便说一句,如果可能的话,将对象存储在cookie而不仅仅是ID中是否安全?cookie只是字符串数据;做到这一点的唯一方法是将它序列化为一个字符串(xml、json、base-64任意二进制文件,等等),但是,如果它与安全信息有任何关系,你不应该真正相信它在cookie中(“我是谁?”)作为:最终用户很容易更改它,并且b:您不希望每个请求都有任何大问题的开销。IMO,服务器缓存这个是正确的;不要把它放在饼干里。您可以使用JSON字符串myObjectJson=newJavaScriptSerializer().Serialize(myObject);varcookie=newHttpCookie("myObjectKey",myObjectJson){Expires=DateTime.Now.AddYears(1)};HttpContext.Response.Cookies.Add(cookie);简短的回答是:Cookie存储字符串,而不是二进制对象。如果确实需要,您可以将对象序列化为字符串或JSON。建议尽可能简单地进行数据的前向和后向传输。请记住:每次我们从浏览器到服务器通信时,您每次都会传递所有数据。您也可以加密此类cookie。内容(json/xml/等)会更安全一些。Marc建议的服务器端缓存可能更好。权衡:增加网络流量(来回传递cookie)与更大的服务器端内存占用和/或辅助存储。顺便说一句:如果确实需要,您可以将二进制文件编码为文本。http://www.codeproject.com/KB/security/TextCoDec.aspx试试这样的东西?StringWriteroutStream=newStringWriter();XmlSerializers=newXmlSerializer(typeof(List>));s.Serialize(outStream,myObj);cookie.Value=outStream.ToString();在cookie中,可以存储字符串类型的值。您可以将对象存储到会话、视图状态或缓存中。但仍然想存储在cookie中,只需使用system.web.script.javascriptserialization类并将整个对象转换为json字符串并将其存储在cookie中。System.Collections.Specialized.NameValueCollectioncookiecoll=newSystem.Collections.Specialized.NameValueCollection();cookiecoll.Add(bizID.ToString(),rate.ToString());HttpCookiecookielist=newHttpCookie("MyListOfCookies");饼干列表。值。添加(cookiecoll);HttpContext.Current.Response.Cookies.Add(cookielist);你可以试试这个:publicvoidAddToCookie(SessionUsersessionUser){varhttpCookie=HttpContext.Current.Response.Cookies["SessionUser"];if(httpCookie!=null){httpCookie["ID"]=sessionUser.ID.ToString();httpCookie["名称"]=sessionUser.Name;httpCookie["Email"]=sessionUser.Email;httpCookie["电话"]=sessionUser.Phone;httpCookie.Expires=DateTime.Now.AddDays(1);要将对象存储在cookie中,我们必须将其转换为字符串化表示(压缩或未压缩),限制为4kb。这个例子演示了如何在cookie中保存一个小的“Purchase”对象(保存/扩展/重置/清除)。我没有使用单独的代码行,而是使用Json用一些数据填充该对象。使用系统;使用System.Collections.Generic;使用System.Web;使用Newtonsoft.Json;公共类客户{publicintid;公共字符串名称;}publicclassOrder{publicintid;公共小数总数;公共客户客户;}publicclassOrderItem{publicintid;公共字符串名称;公开十进制价格;}publicclassBuy{publicOrder订单;公共列表购物车;}staticreadonlystringcookieName=@"buy";protectedoverridevoidOnLoad(EventArgse){base.OnLoad(e);如果(!IsPostBack)Restore_Click(空,空);}protectedvoidSave_Click(objectsender,EventArgse){stringbuy=JsonConvert.SerializeObject(new{order=new{id=1,total=20.10,customer=new{id=1,name="Stackoverflow"}},购物车=new[]{new{id=1,name="Stack",price=10.05},new{id=2,name="Overflow",price=10.05}}});HttpContext.Current.Response.Cookies.Add(newHttpCookie(cookieName,buy){Expires=DateTime.Now.AddDays(7)});StatusLabel.Text="已保存";}protectedvoidProlong_Click(objectsender,EventArgse){HttpCookiecookie=HttpContext.Current.Request.Cookies[cookieName];如果(cookie!=null){cookie.Expires=DateTime.Now.AddDays(7);HttpContext.Current.Response.Cookies.Add(cookie);StatusLabel.Text="延长";}elseStatusLabel.Text="未延长-已过期";}protectedvoidRestore_Click(objectsender,EventArgse){Buybuy=null;HttpCookiecookie=HttpContext.Current.Request.Cookies[cookieName];if(cookie!=null){buy=JsonConvert.DeserializeObject(cookie.Value);StatusLabel.Text="已恢复";}elseStatusLabel.Text="未恢复-已过期";}protectedvoidClearOut_Click(objectsender,EventArgse){HttpCookiecookie=HttpContext.Current.Request.Cookies[cookieName];如果(cookie!=null){cookie.Expires=DateTime.Now.AddMonths(-1);HttpContext.Current.Response.Cookies.Add(cookie);StatusLabel.Text="清除完毕";}否则状态标签。Text="未找到-已过期";}Cookie只存储字符串你可以做什么:varserializer=newSystem.Web.Script.Serialization.JavaScriptSerializer();varjson=serializer.Serialize(user);控制器。响应。SetCookie(newHttpCookie({string_name},json){Expires=false//当你想删除时使用这个?DateTime.Now.AddMonths(-1):DateTime.Now.Add({expiration})});这应该将整个对象插入到cookie中。为了从cookie中读回一个对象:以上是C#学习教程:Howtostoreanobjectinacookie?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注——publicstatic{Object_Name}GetUser(thisControllercontroller){varhttpRequest=controller.Request;如果(httpRequest.Cookies[{cookie_name}]==null){返回null;}else{varjson=httpRequest.Cookies[{cookie_name}].Value;varserializer=newSystem.Web.Script.Serialization.JavaScriptSerializer();varresult=serializer.Deserialize(json);返回结果;}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: