asp.net cookie和session的详细使用

cookie使用代码:

 //设置Cookie
            HttpCookie setCookie = new HttpCookie("test");
            setCookie.Values.Add("Name","Admin");
            Response.Cookies.Add(setCookie);
            setCookie.Expires = DateTime.Now.AddSeconds(5);

            //读取Cookie
            HttpCookie getCookie = Request.Cookies["test"];
            string name;
            if (getCookie!=null)
            {
                name = getCookie.Values["Name"];
            }

            //修改Cookie
            int counter = 0;
            if (Request.Cookies["counter"] == null)
                counter = 0;
            else
                counter = counter + 1;
            Response.Cookies["counter"].Value = counter.ToString();
            Response.Cookies["counter"].Expires = DateTime.Now.AddSeconds(10);

            //删除指定的单个Cookie(利用一个过期的Cookie来代替它)
            HttpCookie delCookie = new HttpCookie("test");
            delCookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(delCookie);

            //删除当前域的所有Cookie
            HttpCookie delCookies;
            int cookies = Request.Cookies.Count;
            for (int i = 0; i <= cookies; i++)
            {
                delCookies = Request.Cookies[i];
                delCookies.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(delCookies);
            }
session使用代码:

  //在Session里面存储一个DataSet
            System.Data.DataSet dataSet = new System.Data.DataSet();
            Session["dataSet"] = dataSet;
            //从Session里取得该DataSet
            dataSet = (System.Data.DataSet)Session["dataSet"];
"SessionID:"+Session.SessionID.ToString()+"
"; "Session的数量:"+Session.Count.ToString()+"
"; "Session的模式:"+Session.Mode.ToString()+"
"; "Session的有效期:"+Session.Timeout.ToString()+"分钟";


你可能感兴趣的:(C#)