.NET cookie 使用方法

创建 C# cookie,两种方法

Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie("lastVisit"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);

 


二、读取代码 ,http://www.cnblogs.com/firstcsharp/archive/2013/06/08/3127209.html【详解】

 

if(Request.Cookies["userName"] != null)
    Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
    HttpCookie aCookie = Request.Cookies["userName"];
    Label1.Text = Server.HtmlEncode(aCookie.Value);
}

 

三、写个MVC ACTION  关于删除 增加 cookie 的

   public ActionResult Index()
        {


            if (Request.Cookies["userName"] != null)
            {
                HttpCookie f = Request.Cookies["userName"];


                int limit = Request.Cookies.Count;    //获取当前网站所有cookie名字
                for (int i = 0; i < limit; i++)
                {
                    Response.Write(Server.HtmlEncode(Request.Cookies[i].Name));
                }


                Request.Cookies.Remove("userName"); //删除某个cookie名字

                Response.Write(Request.Cookies["userName"] == null ? "userName被删除了":Request.Cookies["userName"].Value);

            }
            else
            {
                HttpCookie aCookie = new HttpCookie("userName");
                aCookie.Value = DateTime.Now.ToString();
                aCookie.Expires = DateTime.Now.AddDays(1);

                Response.Cookies.Add(aCookie);
                HttpCookie p = new HttpCookie("aaaaa");
                p.Value = "123";
                p.Expires = DateTime.Now.AddDays(1);


                Response.Cookies.Add(p);

            }

            return View();
        }

四、c# 与 javascript 增加的cookie 可以相互使用

  <script>  var date = new Date();
        date.setDate(date.getDate() + 7);
        document.cookie = ‘user=‘ + encodeURIComponent("cpuaaa") + ";path=" + "C:/Documents%20and%20Settings/Administrator/%E6%A1%8C%E9%9D%A2/cpu;expires=" + date;


        document.cookie = "url=cpu.com";
        document.cookie = "gg=cpugege.com";

//以上为增加多个 cookie

        alert(document.cookie);

//获取某个字段的COOKIE方法

        function getCookie(name) {
            var cookieName = encodeURIComponent(name) + ‘=‘;
            var cookieStart = document.cookie.indexOf(cookieName);//indexOf(找到这个字符串的位置)
            if (cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf(";", cookieStart);//indexOf(索引到某处,从某位置开始索引(数字))
                if (cookieEnd == -1) {

                    cookieEnd = document.cookie.length;

                }
            }
            return document.cookie.substring(cookieStart + cookieName.length, cookieEnd);
        }

        alert(getCookie(‘aaaaa‘));// 调用测试
        alert(getCookie(‘url‘));


    </script>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。