zoukankan      html  css  js  c++  java
  • asp.net操作cookie

    一、添加cookie 

     

    C# 代码   复制
    
    //方式1:
    Response.Cookies["username"].value="gggg";
    Response.Cookies["username"].Expires=DateTime.MaxValue; 
    
    //方式2:
    HttpCookie acookie = new HttpCookie("last");
    acookie.Value="a";
    acookie..Expires=DateTime.MaxValue; 
    Response.Cookies.Add(acookie);
    
    //多值Cookie的写法 
    
    //方式1:
    Response.Cookies["userinfo1"]["name"].value="aaa";
    Response.Cookies["userinfo1"]["last"].value="a";
    Response.Cookies["userinfo1"].Expires=DateTime.MaxValue; 
    
    //方式2:
    HttpCookie cookie = new HttpCookie("userinfo1");
    cookie.Values["name"]="aaa";
    cookie.Values["last"]="a";
    cookie.Expires=DateTime.MaxValue; 
    //cookie.Expires = System.DateTime.Now.AddDays(1);//设置过期时间  1天
    Response.Cookies.Add(cookie);
    

     

    二、读取Cookie 

    Internet Explorer 将站点的 Cookie 保存在文件名格式为 <user>@<domain>.txt 的文件中,其中 <user> 是您的帐户名。

     

    C# 代码   复制
    
    if (Request.Cookies["userName"]!=null)
    {
      string str = Request.Cookies("userName").Value; 
    }
    
    //多值Cookie的读取
    if (Request.Cookies["userInfo1"]!=null )
    {
      string name=Request.Cookies["userInfo1"]["name"];
      string last=Request.Cookies["userInfo1"]["last"]; 
    }
    
    
    //读取 Cookie 集合
    for(int i = 0 ;i<Request.Cookies.Count ;i++)
    {
        HttpCookie cookies = Request.Cookies;
        Response.Write("name="+cookies.Mame+"<br/>");
        if (cookies.HasKeys )//是否有子键
        {
            System.Collections.Specialized.NameValueCollection NameColl 
                                                 = aCookie.Values ;
            for(int j=0;j<NameColl.Count;j++)
            {
                Response.Write("子键名="+ NameColl.AllKey[j] +"<br/>");
                Response.Write("子键值="+ NameColl[j] +"<br/>");
            }
    
        }
        else
        {
            Response.Write("value="+cookies.Value+"<br/>");        
        }
    }
    


    注意:在获取Cookie的值之前,应该确保该 Cookie 确实存在。否则,您将得到一个异常

     

    三、修改 Cookie 


    修改的方法与创建方法相同

     

    四、删除 Cookie 


    将其有效期设置为过去的某个日期。当浏览器检查 Cookie 的有效期时,就会删除这个已过期的 Cookie。
     

     
    C# 代码   复制
    
    //删除cookie下的属性
    
    
     HttpCookie acookie=Request.Cookies["Info"];
     acookie.Values.Remove("userid");
     acookie.Expires = DateTime.Now.AddDays(1);
     Response.Cookies.Add(acookie);        
    
    //删除所有cookie,就是设置过期时间为现在就行了
    
    
     int limit=Request.Cookies.Count - 1;
     for(int i=0;i<limit;i++)
     {
         acookie = Request.Cookies(i)
         acookie.Expires = DateTime.Now.AddDays(-1)
         Response.Cookies.Add(acookie)
     }    
    

     

    五、ASP.NET对Cookie操作的公用类

     

     
    C# 代码   复制
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Collections.Specialized;
    
     
    namespace Core.Common.Web
    {
    
        /// <summary>
        /// Cookie静态操作类
        /// </summary>
    
        public static class Cookie
        {
    
            #region 静态方法
    
            /// <summary>
            /// 创建或修改COOKIE对象并赋Value值
            /// </summary>
    
            /// <param name="strCookieName">COOKIE对象名</param>
            /// <param name="strValue">COOKIE对象Value值</param>
            /// <remarks>
            /// 对COOKIE修改必须重新设Expires
            /// </remarks>
    
            public static void SetObject(string strCookieName, string strValue)
            {
                SetObject(strCookieName, 1, strValue);
            }
    
     
            /// <summary>
            /// 创建或修改COOKIE对象并赋Value值
            /// </summary>
    
            /// <param name="strCookieName">COOKIE对象名</param>
            /// <param name="iExpires">
            /// COOKIE对象有效时间(秒数)
            /// 1表示永久有效,0和负数都表示不设有效时间
            /// 大于等于2表示具体有效秒数
            /// 86400秒 = 1天 = (60*60*24)
            /// 604800秒 = 1周 = (60*60*24*7)
            /// 2593000秒 = 1月 = (60*60*24*30)
            /// 31536000秒 = 1年 = (60*60*24*365)
            /// </param>
            /// <param name="strValue">COOKIE对象Value值</param>
            /// <remarks>
            /// 对COOKIE修改必须重新设Expires
            /// </remarks>
    
            public static void SetObject(string strCookieName, int iExpires, string strValue)
            {
                HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
                objCookie.Value = HttpContext.Current.Server.UrlEncode(strValue.Trim());
    
                if (iExpires > 0)
                {
                    if (iExpires == 1)
                    {
                        objCookie.Expires = DateTime.MaxValue;
                    }
                    else
                    {
                        objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                    }
                }
                HttpContext.Current.Response.Cookies.Add(objCookie);
            }
    
     
    
            /// <summary>
            /// 创建COOKIE对象并赋多个KEY键值
            /// </summary>
    
            /// <param name="strCookieName">COOKIE对象名</param>
            /// <param name="iExpires">
            /// COOKIE对象有效时间(秒数)
            /// </param>
            /// <param name="KeyValue">键/值对集合</param>
    
            public static void SetObject(string strCookieName, int iExpires, NameValueCollection KeyValue)
            {
                HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
    
                foreach (string key in KeyValue.AllKeys)
                {
                    objCookie[key] = HttpContext.Current.Server.UrlEncode(KeyValue[key].Trim());
                }
                if (iExpires > 0)
                {
                    if (iExpires == 1)
                    {
                        objCookie.Expires = DateTime.MaxValue;
                    }
                    else
                    {
                        objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                    }
                }
                HttpContext.Current.Response.Cookies.Add(objCookie);
            }
    
     
    
            /// <summary>
            /// 创建或修改COOKIE对象并赋Value值
            /// </summary>
            /// <param name="strCookieName">COOKIE对象名</param>
            /// <param name="iExpires">
            /// COOKIE对象有效时间(秒数)
            /// </param>
            /// <param name="strDomain">作用域</param>
            /// <param name="strValue">COOKIE对象Value值</param>
            /// <remarks>
            /// 对COOKIE修改必须重新设Expires
            /// </remarks>
    
            public static void SetObject(string strCookieName, int iExpires, string strValue, string strDomain)
            {
                HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
                objCookie.Value = HttpContext.Current.Server.UrlEncode(strValue.Trim());
                objCookie.Domain = strDomain.Trim();
    
                if (iExpires > 0)
                {
                    if (iExpires == 1)
                    {
                        objCookie.Expires = DateTime.MaxValue;
                    }
                    else
                    {
                        objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                    }
                }
                HttpContext.Current.Response.Cookies.Add(objCookie);
            }
    
     
    
            /// <summary>
            /// 创建COOKIE对象并赋多个KEY键值
            /// </summary>
            /// <param name="strCookieName">COOKIE对象名</param>
            /// <param name="iExpires">
            /// COOKIE对象有效时间(秒数)
            /// </param>
            /// <param name="strDomain">作用域</param>
            /// <param name="KeyValue">键/值对集合</param>
    
            public static void SetObject(string strCookieName, int iExpires, NameValueCollection KeyValue, string strDomain)
    
            {
    
                HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
                foreach (string key in KeyValue.AllKeys)
                {
                    objCookie[key] = HttpContext.Current.Server.UrlEncode(KeyValue[key].Trim());
                }
                objCookie.Domain = strDomain.Trim();
                if (iExpires > 0)
                {
                    if (iExpires == 1)
                    {
                        objCookie.Expires = DateTime.MaxValue;
                    }
                    else
                    {
                        objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                    }
                }
                HttpContext.Current.Response.Cookies.Add(objCookie);
            }
    
     
    
            /// <summary>
            /// 读取Cookie某个对象的Value值,返回Value值
            /// </summary>
            /// <param name="strCookieName">Cookie对象名称</param>
            /// <returns>Value值,如果对象本就不存在,则返回 null</returns>
    
            public staticstring GetValue(string strCookieName)
            {
                if (HttpContext.Current.Request.Cookies[strCookieName] ==null)
                {
                    returnnull;
                }else{
                    return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strCookieName].Value);
                }
            }///<summary>/// 读取Cookie某个对象的某个Key键的键值
            ///</summary>///<param name="strCookieName">Cookie对象名称</param>///<param name="strKeyName">Key键名</param>///<returns>Key键值,如果对象或键值就不存在,则返回 null</returns>
    publicstaticstring GetValue(string strCookieName, string strKeyName)
            {
                if (HttpContext.Current.Request.Cookies[strCookieName] ==null)
                {
                    returnnull;
                }else{
                    string strObjValue = HttpContext.Current.Request.Cookies[strCookieName].Value;
                    string strKeyName2 = strKeyName +"=";
    
                    if (strObjValue.IndexOf(strKeyName2) ==-1)
                    {
                        returnnull;
                    }else{
                        return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strCookieName][strKeyName]);
                    }
                }
            }///<summary>/// 修改某个COOKIE对象某个Key键的键值或给某个COOKIE对象添加Key键
            ///</summary>///<param name="strCookieName">Cookie对象名称</param>///<param name="strKeyName">Key键名</param>///<param name="KeyValue">Key键值</param>///<param name="iExpires">/// COOKIE对象有效时间(秒数)
            ///</param>///<returns>如果对象本就不存在,则返回 false</returns>
    publicstaticbool Edit(string strCookieName, string strKeyName, string KeyValue, int iExpires)
            {
                if (HttpContext.Current.Request.Cookies[strCookieName] ==null)
                {
                    returnfalse;
                }else{
                    HttpCookie objCookie = HttpContext.Current.Request.Cookies[strCookieName];
                    objCookie[strKeyName] = HttpContext.Current.Server.UrlEncode(KeyValue.Trim());
    
                    if (iExpires >0)
                    {
                        if (iExpires ==1)
                        {
                            objCookie.Expires = DateTime.MaxValue;
                        }else{
                            objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                        }
                    }
                    HttpContext.Current.Response.Cookies.Add(objCookie);
                    returntrue;
    
                }
            }///<summary>/// 删除COOKIE对象
            ///</summary>///<param name="strCookieName">Cookie对象名称</param>
    publicstaticvoid Delete(string strCookieName)
            {
                HttpCookie objCookie =new HttpCookie(strCookieName.Trim());
                objCookie.Expires = DateTime.Now.AddYears(-5);
                HttpContext.Current.Response.Cookies.Add(objCookie);
            }///<summary>/// 删除某个COOKIE对象某个Key子键
            ///</summary>///<param name="strCookieName">Cookie对象名称</param>///<param name="strKeyName">Key键名</param>///<param name="iExpires">/// COOKIE对象有效时间(秒数)
            ///</param>///<returns>如果对象本就不存在,则返回 false</returns>
    publicstaticbool Delete(string strCookieName, string strKeyName, int iExpires)
            {
                if (HttpContext.Current.Request.Cookies[strCookieName] ==null)
                {
                    returnfalse;
                }else{
                    HttpCookie objCookie = HttpContext.Current.Request.Cookies[strCookieName];
                    objCookie.Values.Remove(strKeyName);
                    if (iExpires >0)
                    {
                        if (iExpires ==1)
                        {
                            objCookie.Expires = DateTime.MaxValue;
                        }else{
                            objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
                        }
                    }
                    HttpContext.Current.Response.Cookies.Add(objCookie);
                    returntrue;
                }
            }#endregion
    
        }
    }
  • 相关阅读:
    狡猾的商人
    差分约束系统
    【模板】负环
    关于Java8的精心总结
    rabbitmq+sleuth+zinkip 分布式链路追踪
    Linux下一只五颜六色的「猫」
    整理 Linux下列出目录内容的命令
    从封装变化的角度看设计模式——组件协作
    从封装变化的角度看设计模式——接口隔离
    从封装变化的角度看设计模式——对象创建
  • 原文地址:https://www.cnblogs.com/ranran/p/4057141.html
Copyright © 2011-2022 走看看