Cookie与Session

 

 //修改cookie
        public void Login(string userName,string userPwd)
        {         
            //判断cookie是否为空,如果为空则需要重新创建           
            //var cookie = Request.Cookies["UserLogin"]; 直接获取cookie
           // var cookie = new HttpCookie("UserLogin");  创建cookie
            var cookie = Request.Cookies["UserLogin"] ?? new HttpCookie("UserLogin");
            cookie.Values.Set("userName", userName);
            cookie.Values.Set("userPwd", userPwd);
            cookie.Expires = DateTime.Now.AddDays(1);//设置过期时间
            Response.Cookies.Set(cookie);                      
        }

        //添加cookie
        public void Add(string userName, string userPwd)
        {
            //判断cookie是否为空,如果为空则需要重新创建
            var cookie = Request.Cookies["UserLogin"] ?? new HttpCookie("UserLogin");
            cookie.Values.Add("userName", userName);//数据会累计叠加
            cookie.Values.Add("userPwd", userPwd);
            cookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Set(cookie);       
        }

        //获取cookie
        public void Get()
        {
            var cookie = Request.Cookies["UserLogin"];
            var name = cookie.Values["userName"];
            var pwd = cookie.Values["userPwd"];
        }

        //删除cookie
        public void Delete()
        {
            var cookie = Request.Cookies["UserLogin"];
            //方法一
            cookie.Values.Remove("userName");
            cookie.Values.Remove("userPwd");
            //方法二
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Set(cookie);    
        }
        //设置Session
        public void SessionSet()
        {
            //向session中设置值
            Session["userName"] = "大王";
            //获取Session中的值
            var name = Session["userName"];
        }

 

Cookie使用例子

http://www.cnblogs.com/kevin-top/archive/2010/07/04/1770726.html

 

posted @ 2014-11-28 15:06  逍遥帝君  阅读(209)  评论(0编辑  收藏  举报