C#中的Cookie 添加 读取 删除
设置Cookie
public void AddCookie() { //方法一: HttpCookie Cookie1 = new HttpCookie("CookieName"); Cookie1.Expires = DateTime.Now.AddDays(1);//设置过期时间 Cookie1.Value = "Value"; Response.Cookies.Add(Cookie1);//响应一个Cookies //System.Web.HttpContext.Current.Response.Cookies.Add(Cookie1);//作用同 Response.Cookies.Add(Cookie1),响应一个Cookies //方法二: Response.Cookies["CookieName"].Value = "Value"; // Response.Cookies["CookieName"].Values["Key"] = "Value";//存多值 Response.Cookies["CookieName"].Expires = DateTime.Now.AddDays(1);//设置过期时间 //方法三: HttpCookie cookie3 = new HttpCookie("CookieName"); DateTime dt = DateTime.Now; //获取当前时间 TimeSpan ts = new TimeSpan(0, 0, 1, 0, 0);//过期时间为1分钟 cookie3.Expires = dt.Add(ts);//设置过期时间 cookie3.Values.Add("Key", "Value"); cookie3.Values.Add("Key", "Value"); //cookie3.Values.Set("Key", "Value");//设置cookie某项的值 Response.AppendCookie(cookie3); //响应一个Cookies //注:如果使用response.Cookies创建cookie就不用写System.Web.HttpContext.Current.Response.Cookies了。 }
获取Cookie
public void ReadCookie() { //方法一: HttpCookie cookies1 = Request.Cookies["CookieName"]; string Values1 = cookies1.Value; //string Values 1= cookies.Values["Key"];//获取多值 //方法二: string Values2 = Request.Cookies["CookieName"].Value; //string Values2 = Request.Cookies["CookieName"].Values["Key"];//获取多值 //方法三:(获取多值) string Values3 = Server.UrlDecode(Request.Cookies["CookieName"]["Key"]); //System.Web.HttpContext.Current.Request.Cookies["CookieName"];//同Request.Cookies }
修改Cookie
public void UpdateCookie() { //修改只需要重新给要修改的cookie赋值就行,这样旧的就会被覆盖掉。 //所以这里只写一种方法,更多请参考创建cookie HttpCookie Cookie = Request.Cookies["CookieName"]; Cookie.Expires = DateTime.Now.AddDays(1);//设置过期时间 Cookie.Value = "Value";//设置值 Response.Cookies.Add(Cookie);//响应一个Cookies }
删除Cookie
public void DeleteCookie() { //删除cookie只需修改的cookie的过期时间(expires)过去的时间即可 //所以这里只写一种方法,更多请参考创建cookie HttpCookie Cookie = Request.Cookies["CookieName"]; Cookie.Expires = DateTime.Now.AddDays(-1);//设置过期时间 Response.Cookies.Add(Cookie);//响应一个Cookies }
- 注意:对Cookie进行操作时应先判断cookie不为空
- 注意:当Cookie存中文出现乱码,则在存放时给中文编码,读取时解码即可,如Cookie.setCookie("name", Server.UrlEncode("Value"),1)
- 注意:只要不给cookie设置过期时间,cookie在浏览器关闭的时候自动失效
认真工作、认真生活,努力做最好的自己!!!