zoukankan      html  css  js  c++  java
  • C#操作cookie

    创建Cookie

                       HttpCookie cookie = new HttpCookie("MyCook");//初使化并设置Cookie的名称
                        DateTime dt = DateTime.Now;
                        TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);//过期时间为1天
                        cookie.Expires = dt.Add(ts);//设置过期时间
                        cookie.Values.Add("uid", uid);  //添加cookie
                        Response.AppendCookie(cookie);

    读取Cookie

             if (Request.Cookies["MyCook"] != null)
                {
                    ViewData["Uid"] = Request.Cookies["MyCook"]["uid"]; //输出cookie
                }

    修改Cookie

     //获取客户端的Cookie对象
        HttpCookie cookie= Request.Cookies["MyCook"];
            
        if (cookie!= null)
        {
          //修改Cookie的两种方法
          cookie.Values["uid"] = "134626655";
          cookie.Values.Set("userid", "134626655");
    
          //往Cookie里加入新的内容
          cookie.Values.Set("newid", "newValue");
          Response.AppendCookie(cookie);
        }      

    删除Cookie

    HttpCookie cookie= Request.Cookies["MyCook"];
        if (cookie!= null)
        {
          if (!CheckBox1.Checked)
          {
            cookie.Values.Remove("uid");//移除键值为uid的值
          }
          else
          {
            TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
            cookie.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在
          }
          Response.AppendCookie(cookie);
        }

    设置Cookie过期的时间的TimeSpan

    [Serializable]
    public TimeSpan(
       int days,
       int hours,
       int minutes,
       int seconds
    );
  • 相关阅读:
    web.config配置数据库连接 【转】
    WEB API 返回类型设置为JSON 【转】
    ASP.NET WebAPI 路由规则与POST数据 【转】
    ASP.NET Web API路由规则(二) 【转】
    七天学会ASP.NET MVC(七)——创建单页应用 【转】
    jumpserver-v0.5.0 应用图解
    jumpserverv0.5.0 基于 CentOS7安装部署
    tar: Removing leading `/' from member names
    redis cli命令
    zabbix监控redis的key值
  • 原文地址:https://www.cnblogs.com/llxy/p/4078563.html
Copyright © 2011-2022 走看看