COOKIEs的创建:
在客户端创建一个username的COOKIEs,其值为oneday,有效期为1天.
方法1:
方法2:
COOKIEs的读取:
无子键读取:
有子键读取:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class COOKIE
{
///
/// COOKIEs赋值
///
/// 主键
/// 键值
/// 有效天数
///
public bool setCOOKIE(string strName, string strValue, int strDay)
{
try
{
HttpCOOKIE COOKIE = new HttpCOOKIE(strName);
//COOKIE.Domain = ".xxx.com";//当要跨域名访问的时候,给COOKIE指定域名即可,格式为.xxx.com
COOKIE.Expires = DateTime.Now.AddDays(strDay);
COOKIE.Value = strValue;
System.Web.HttpContext.Current.Response.COOKIEs.Add(COOKIE);
return true;
}
catch
{
return false;
}
}
///
/// 读取COOKIEs
///
/// 主键
///
public string getCOOKIE(string strName)
{
HttpCOOKIE COOKIE = System.Web.HttpContext.Current.Request.COOKIEs[strName];
if (COOKIE != null)
{
return COOKIE.Value.ToString();
}
else
{
return null;
}
}
///
/// 删除COOKIEs
///
/// 主键
///
public bool delCOOKIE(string strName)
{
try
{
HttpCOOKIE COOKIE = new HttpCOOKIE(strName);
//COOKIE.Domain = ".xxx.com";//当要跨域名访问的时候,给COOKIE指定域名即可,格式为.xxx.com
COOKIE.Expires = DateTime.Now.AddDays(-1);
System.Web.HttpContext.Current.Response.COOKIEs.Add(COOKIE);
return true;
}
catch
{
return false;
}
}
}
注意:当COOKIE存中文出现乱码,则在存放时给中文编码,如COOKIE.setCOOKIE("name", Server.UrlEncode("aaa"),1),读取时解码即可
另外:只要不给COOKIE设置过期时间,COOKIE在浏览器关闭的时候自动失效
public class COOKIE
{
///
/// COOKIEs赋值
///
/// 主键
/// 键值
/// 有效天数
///
public bool setCOOKIE(string strName, string strValue, int strDay)
{
try
{
HttpCOOKIE COOKIE = new HttpCOOKIE(strName);
//COOKIE.Domain = ".xxx.com";//当要跨域名访问的时候,给COOKIE指定域名即可,格式为.xxx.com
COOKIE.Expires = DateTime.Now.AddDays(strDay);
COOKIE.Value = strValue;
System.Web.HttpContext.Current.Response.COOKIEs.Add(COOKIE);
return true;
}
catch
{
return false;
}
}
///
/// 读取COOKIEs
///
/// 主键
///
public string getCOOKIE(string strName)
{
HttpCOOKIE COOKIE = System.Web.HttpContext.Current.Request.COOKIEs[strName];
if (COOKIE != null)
{
return COOKIE.Value.ToString();
}
else
{
return null;
}
}
///
/// 删除COOKIEs
///
/// 主键
///
public bool delCOOKIE(string strName)
{
try
{
HttpCOOKIE COOKIE = new HttpCOOKIE(strName);
//COOKIE.Domain = ".xxx.com";//当要跨域名访问的时候,给COOKIE指定域名即可,格式为.xxx.com
COOKIE.Expires = DateTime.Now.AddDays(-1);
System.Web.HttpContext.Current.Response.COOKIEs.Add(COOKIE);
return true;
}
catch
{
return false;
}
}
}
示例:
注意:当COOKIE存中文出现乱码,则在存放时给中文编码,如COOKIE.setCOOKIE("name", Server.UrlEncode("aaa"),1),读取时解码即可
另外:只要不给COOKIE设置过期时间,COOKIE在浏览器关闭的时候自动失效