C# Web开发 标准读写Cookies的方法 支持跨二级域和虚拟目录

  在博客园看到另外一个朋友的可跨二级域操作Cookies方法,在它基础上完善了一下,现发出来

 我参考的哪位朋友的文章地址是:http://www.cnblogs.com/voswin/articles/1281520.html

 

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->      ///   <summary>
    
///  添加/更新 Cookies
    
///   </summary>
    
///   <param name="_domain"></param>
    
///   <param name="_cookiepath"></param>
    
///   <param name="_key"></param>
    
///   <param name="_cookiename"></param>
    
///   <param name="_value"></param>
     public   static   void  SetUserCookies( string  _domain,  string  _cookiepath,  string  _key,  string  _cookiename,  string  _value, DateTime _expires)
    {

        HttpCookie cookie 
=  HttpContext.Current.Request.Cookies[_key];
        
        
// 防止中文乱码
        _value  =  System.Web.HttpUtility.UrlEncode(_value);
        
// 加密
        _value  =  DESEncrypt.Encrypt(_value);

        
if  (cookie  ==   null )
        {
            cookie 
=   new  HttpCookie(_key);
            cookie.Domain 
=  _domain;
            cookie.Path 
=  _cookiepath;
            cookie.Expires 
=  _expires;

            cookie.Values.Add(_cookiename, _value);                
            HttpContext.Current.Response.AppendCookie(cookie);

        }
        
else
        {

            cookie.Domain 
=  _domain;
            cookie.Path 
=  _cookiepath;
            cookie.Expires 
=  _expires;

            
if  (cookie.Values[_cookiename]  !=   null )
            {  
                cookie.Values.Set(_cookiename, _value);
            }
            
else
            {

                cookie.Values.Add(_cookiename, _value);
            }
            HttpContext.Current.Response.SetCookie(cookie);
            
        }

    }
    
///   <summary>
    
///  读取Cookies
    
///   </summary>
    
///   <param name="_key"></param>
    
///   <param name="_cookiename"></param>
    
///   <returns></returns>
     public   static   string  GetUserCookies( string  _key,  string  _cookiename)
    {

        HttpCookie cookie 
=  HttpContext.Current.Request.Cookies[_key];
        
        
if  (cookie  !=   null )
        {

            
string  _value  =  cookie.Values.Get(_cookiename);

            
if  ( ! string .IsNullOrEmpty(_value))
            {
                
// 防止中文乱码
                _value  =  System.Web.HttpUtility.UrlDecode(_value);
                
// 解密
                _value  =  DESEncrypt.Decrypt(_value);
                
return  _value;
            }
            
else
            {
                
return   "" ;
            }
        }
        
else
        {
            
return   "" ;
        }

    }
    
///   <summary>
    
///  清除Cookies
    
///   </summary>
    
///   <param name="_domain"></param>
    
///   <param name="_cookiepath"></param>
    
///   <param name="key"></param>
     public   static   void  ClearUserCookies( string  _domain,  string  _cookiepath,  string  _key)
    {
        HttpCookie cookie 
=  HttpContext.Current.Request.Cookies[_key];
        
if  (cookie  !=   null )
        {
            cookie.Values.Clear();

            cookie.Domain 
=  _domain;
            cookie.Path 
=  _cookiepath;
            cookie.Expires 
=  DateTime.Now.AddDays( - 1 );

            HttpContext.Current.Response.SetCookie(cookie);
        }

    }

 

加密Cookies和解密Cookies方法:

 

ContractedBlock.gif ExpandedBlockStart.gif 加密/解密方法 DESEncrypt
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->    public class DESEncrypt
    {
        
#region ========加密========

        
/// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="Text"></param>
        
/// <returns></returns>
        public static string Encrypt(string Text)
        {
            
return Encrypt(Text, "lixyvip");
        }
        
/// <summary> 
        
/// 加密数据 
        
/// </summary> 
        
/// <param name="Text"></param> 
        
/// <param name="sKey"></param> 
        
/// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            
byte[] inputByteArray;
            inputByteArray 
= Encoding.Default.GetBytes(Text);
            des.Key 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            des.IV 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            CryptoStream cs 
= new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 
0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret 
= new StringBuilder();
            
foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat(
"{0:X2}", b);
            }
            
return ret.ToString();
        }

        
#endregion

        
#region ========解密========


        
/// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="Text"></param>
        
/// <returns></returns>
        public static string Decrypt(string Text)
        {
            
return Decrypt(Text, "lixyvip");
        }
        
/// <summary> 
        
/// 解密数据 
        
/// </summary> 
        
/// <param name="Text"></param> 
        
/// <param name="sKey"></param> 
        
/// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            
try
            {
                DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
                
int len;
                len 
= Text.Length / 2;
                
byte[] inputByteArray = new byte[len];
                
int x, i;
                
for (x = 0; x < len; x++)
                {
                    i 
= Convert.ToInt32(Text.Substring(x * 22), 16);
                    inputByteArray[x] 
= (byte)i;
                }
                des.Key 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
                des.IV 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
                System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
                CryptoStream cs 
= new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 
0, inputByteArray.Length);
                cs.FlushFinalBlock();
                
return Encoding.Default.GetString(ms.ToArray());
            }
            
catch 
            {
                
return Text;
            }
        }

        
#endregion
    }

 

 

读取当前客户机器所有的Cookies代码:

 

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->              string [] keyArr  =  HttpContext.Current.Request.Cookies.AllKeys;
            
for  ( int  c  =   0 ; c  <  keyArr.Length; c ++ )
            {
                Response.Write(HttpContext.Current.Request.Cookies[keyArr[c]].Name);
                Response.Write(
" <br /> " );
                Response.Write(HttpContext.Current.Request.Cookies[keyArr[c]].Expires.ToString());
                Response.Write(
" <br /> " );
                Response.Write(HttpContext.Current.Request.Cookies[keyArr[c]].Value);
                Response.Write(
" <br /> " );
                Response.Write(
" <br /> " );
            }

 

 

 

 使用或自己写重载方法参考示例:

SetUserCookies(SiteInfo.DomainName, "/", "hnce", name, str, DateTime.Now.AddMinutes(miniute));

return GetUserCookies("hnce", name);

ClearUserCookies(SiteInfo.DomainName, "/", "hnce");

 

另外提醒一下,cookie.Values.Add(_cookiename, _value); 跟 cookie.Values[_cookiename] = _value; 这两种方式都可以设置Cookies的值,但是Add和Set方法后,读取要使用Get方法,而Values[]赋值方式,读取要使用HttpContext.Current.Request.Cookies[_key][_cookiename].ToString() 

否则有Cookies读取不了的情况。

 

//下面附参考文章的部分内容说明

//------------------------------------------------------------------------
Cookie有三个属性需要注意一下:
1. Domain  域
2. Path       路径
3. Expires  过期时间

跨域操作需要设置域属性:
Response.Cookies("MyCookie").Domain = "cnblogs.com"; (这里指的是泛域名)
这样在其它二级域名下就都可以访问到了, ASP 和 ASP.NET 测试通过

虚拟目录下访问:
我在ASP端做了下测试,.NET的没试,  如果不指定Path属性, 不同虚拟目录下Cookie无法共享
将Response.Cookies("MyCookie").Path = "/" 就可以了

总的写法:
Response.Cookies("MyCookie").Domain = "cnblogs.com";
Response.Cookies("MyCookie").Path = "/"
Response.Cookies("MyCookie").Expires = Now + 365;
Response.Cookies("MyCookie")("Test") = "test";

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值