asp.net对cookie的操作(前台js和后台c#代码)

asp.net对cookie的操作(前台js和后台c#代码)

(一)

后台C#代码对cookie的操作:

看一下代码

  1.  
    ///////////////////////////////-----cookie创建设置的操作----///////////////////////////////////////////
  2.  
     
  3.  
    Guid gu_id = Guid.NewGuid(); //获取一个guid,用来放入cookie中,做测试用
  4.  
    HttpCookie cookie = new HttpCookie("name1");//创建一个名称为name1的cookie
  5.  
    DateTime dt = DateTime.Now; //获取当前时间
  6.  
    TimeSpan ts = new TimeSpan(0, 0, 0, 20, 0); //过期时间为20秒
  7.  
    cookie.Expires = dt.Add(ts); //设置过期时间(Expires),指定她的过期时间为(dt+20秒)后过期
  8.  
    cookie.Value = gu_id.ToString(); //把gu_id放入cookie
  9.  
    Response.AppendCookie(cookie); //将一个 HTTP Cookie 添加到(客户端)内部 Cookie 集合。
  10.  
     
  11.  
     
  12.  
     
  13.  
    /////////////////////////////-----cookie读取的操作----////////////////////////////////////////////
  14.  
    /*此段代码也一般单独写在其他页面中,因为cookie是放在客户端的,"本页写本页读"的实际情况不易用到*/
  15.  
     
  16.  
    if (Request.Cookies["name1"] != null)
  17.  
    {
  18.  
    Response.Write(Request.Cookies["name1"].Value+"<br/>");//读取name为"name1"的cookie的值
  19.  
    }
  20.  
     
  21.  
     
  22.  
    /////////////////////// /////--------cookie的修改操作----////////// /////////////////////////////
  23.  
    if(Request.Cookies["name1"]!=null)
  24.  
    {
  25.  
    Request.Cookies["name1"].Value = Guid.NewGuid().ToString();//为名字为"name1"的cookie设置新的值
  26.  
    Response.Write(Request.Cookies["name1"].Value);
  27.  
    }

以上代码:两次读取同一个cookie,其值分别为:

0de2084e-75f3-4427-9e6f-8f0b5c446847
c2f1afa0-c1e0-41aa-a29b-cb6519524e9e

删除cookie的方法:

  1.  
    /// <summary>
  2.  
    /// 删除cookie
  3.  
    /// </summary>
  4.  
    /// <param name="key">cookie的key</param>
  5.  
    public void clearCookies(string key) {
  6.  
    HttpCookie cook = new HttpCookie(key);
  7.  
    cook.Expires = DateTime.Now.AddDays(-1);
  8.  
    cook.Values.Clear();
  9.  
    System.Web.HttpContext.Current.Response.Cookies.Set(cook);
  10.  
    }


(二)

再看一下前台js(jquery)对cookie的操作,引入cookie的jquery插件jquery.cookies.js

对cookies的操作在当访问一个网站就无时无刻的都伴随着我们,记录着我们的一举一动,并将不危害用户隐私的信息,将以保存,这样用户就不用去从新再次操作重复的步骤,这样大大方便了客户,也增加了客户对网站的回头率。

jquery.cookie.js 提供了jquery中非常简单的操作cookie的方法。

  • $.cookie('the_cookie'); // 获得cookie
  • $.cookie('the_cookie', 'the_value'); // 设置cookie
  • $.cookie('the_cookie', 'the_value', { expires: 7 }); //设置带时间的cookie,默认情况是按天计算的
  • $.cookie('the_cookie', '', { expires: -1 }); // 删除
  • $.cookie('the_cookie', null); // 删除 cookie
  • $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});//新建一个cookie 包括有效期 路径 域名等

前辈经验

原文地址:https://www.cnblogs.com/cinemaparadiso/p/9719299.html