以下这个方法为什么 每次传入相同名称的strCookieName值。他都重新加入一个同名的cookie对象。而不是覆盖已有的那个对象。。高手指点下。如何写才能让他不已新对象加入。而是修改或者覆盖掉重名的对象
1 public static void SetObject(string strCookieName, int iExpires, string strValue) 2 { 3 HttpCookie objCookie = new HttpCookie(strCookieName.Trim()); 4 objCookie.Value = HttpContext.Current.Server.UrlEncode(strValue.Trim()); 5 if (iExpires > 0) 6 { 7 if (iExpires == 1) 8 { 9 objCookie.Expires = DateTime.MaxValue; 10 } 11 else 12 { 13 objCookie.Expires = DateTime.Now.AddSeconds(iExpires); 14 } 15 } 16 HttpContext.Current.Response.Cookies.Add(objCookie); 17 }
先检查一下同名cookie是否存在,不存在再创建,代码如下:
var cookieName = strCookieName.Trim(); HttpCookie cookie = Request.Cookies[cookieName]; if (cookie == null) { cookie = new HttpCookie(cookieName); }