您的位置:首页 > 其它

Cookie的使用

2013-12-14 10:18 113 查看

(1)Asp.Net 中保存Cookies

通常,我们使用Request和Response对象来直接操作Cookies:

写入Cookies:

Response.Cookies["k1"].Value = "k1Value";
Response.Cookies["k2"]["k2-1"] = "k2-1Value";
Response.Cookies.Add(new HttpCookie("k3", "k3Value"));

读取Cookies:

Request["k1"] ;
Request.Cookies["k1"].Value ;
Request.Cookies["k2"]["k2-1"];
Request.Cookies.Get(0).Value;

注意Request["k1"]这个大家熟悉的获取get和post参数的方法,同时还能够获取Cookies的值!

另外上面语句中的有些是必须通过Value属性访问的,有些则不需要。

(2)以对象方式保存Cookies

下面提供一个可以以对象方式整体保存Cookies的工具类。并且只占用一条Cookies,所有的属性都存在子键上。


源代码:  


/// <summary>
/// Cookies基类。将需要保存Cookies的数据类此类派生,可以将强类型对象在Cookies中的保存和读取。
/// </summary>
/// <remarks>
/// 2009.8.6    ziqiu.zhang     created
/// </remarks>
/// <example>
/// 假设MyCookiesInfo是从 从Cookies中获取对象:
/// <code>
///     CookieInfo item = new CookieInfo(); //new以后已经从Cookies中构造了对象。
/// </code>
/// 将对象保存在Cookies中:
/// <code>
///     CookieInfo item = new CookieInfo();
///     item.value = "test value";
///     item.SetCookies("1"); //Cookies有效期为1天
/// </code>
/// </example>
[System.Serializable]
public class CookieInfo
{

#region ==================== Constructed Method ====================
/// <summary>
/// 构造函数
/// </summary>
public CookieInfo()
{

}
#endregion

#region ==================== Public Method ====================
/// <summary>
/// 得到当前Cookies的过期时间
/// </summary>
/// <returns>过期时间</returns>
public DateTime GetExpiresTime()
{
string cookieName = GetType().ToString();
if (HttpContext.Current.Request.Cookies[cookieName] != null)
{
return HttpContext.Current.Request.Cookies[cookieName].Expires;
}
return DateTime.MinValue;
}

/// <summary>
/// 保存Cookies,过期时间为浏览器关闭则失效。
/// </summary>
/// <param name="expiresTime">Cookies过期事件</param>
/// <returns>是否保存成功</returns>
public bool Save()
{
return this.Save(DateTime.MinValue);
}

/// <summary>
/// 保存Cookies,需要指定过期时间。
/// </summary>
/// <param name="expiresTime">Cookies过期事件</param>
/// <returns>是否保存成功</returns>
public bool Save(DateTime expiresTime)
{
string CookieName = GetType().ToString();
HttpCookie SessionCookie = null;

//对 SessionId 进行备份.
if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
{
string SesssionId = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value.ToString();
SessionCookie = new HttpCookie("ASP.NET_SessionId");
SessionCookie.Value = SesssionId;

}
//设定cookie 过期时间.
DateTime dtExpiry = expiresTime;
HttpContext.Current.Response.Cookies[CookieName].Expires = dtExpiry;

//设定cookie 域名.
string domain = string.Empty;
if (HttpContext.Current.Request.Params["HTTP_HOST"] != null)
{
//domain = "www.elong.com";
domain = HttpContext.Current.Request.Params["HTTP_HOST"].ToString();
}

//如果是www.elong.com或多级域名,需要转化为elong.com
if (domain.IndexOf(".") > -1)
{
string[] temp = domain.Split('.');

if (temp.Length >= 3)
{
domain = temp[temp.Length - 2].Trim() + "." + temp[temp.Length - 1].Trim();
}

HttpContext.Current.Response.Cookies[CookieName].Domain = domain;
}

//把类的属性, 写入Cookie.
PropertyInfo[] Propertys = GetType().GetProperties();

foreach (PropertyInfo pi in Propertys)
{
object oj = pi.GetValue(this, null);
Type type = pi.PropertyType;
string valueStr = string.Empty;

if (oj != null && oj.ToString() != string.Empty)
{
if (type == Type.GetType("System.DateTime"))
{
valueStr = ((DateTime)oj).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
else
{
valueStr = oj.ToString();
}

HttpContext.Current.Response.Cookies[CookieName][pi.Name] = HttpUtility.UrlEncode(valueStr);
}

}

//如果cookie总数超过20 个, 重写ASP.NET_SessionId, 以防Session 丢失.
if (HttpContext.Current.Request.Cookies.Count > 20 && SessionCookie != null)
{
if (SessionCookie.Value != string.Empty)
{
HttpContext.Current.Response.Cookies.Remove("ASP.NET_SessionId");
HttpContext.Current.Response.Cookies.Add(SessionCookie);
}
}

return true;
}

/// <summary>
/// 找回Cookie值
/// </summary>
public void Load()
{
string cookieValue = string.Empty;
string CookieName = GetType().ToString();

//通过遍历属性, 从cookie 中找回值, 回写到属性.
PropertyInfo[] Propertys = GetType().GetProperties();

foreach (PropertyInfo pi in Propertys)
{
try
{
cookieValue = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName][pi.Name].ToString());
}
catch
{
cookieValue = string.Empty;
}

if (pi.CanWrite && cookieValue != null && cookieValue != string.Empty)
{
try
{
object obb = cookieValue;
Type type = pi.PropertyType;

obb = Convert.ChangeType(obb, type);
pi.SetValue(this, obb, null);
}
catch { }

}
}

}
#endregion

}



使用


首先说明如何使用此类。

为想要保存在Cookies中的类建立模型,并且继承自CookieInfo即可。比如下面建立了MyCookieInfo类,其中包含属性pkid,TestValue和TestDateTime:

 

/// <summary>
/// 保存Cookies的数据对象
/// </summary>
[System.Serializable]
public class MyCookieInfo : CookieInfo
{
private int m_Pkid = 0;
public int Pkid
{
get
{
return m_Pkid ;
}
set
{
m_Pkid = value ;
}
}

private string m_TestValue = "";
public string TestValue
{
get
{
return m_TestValue;
}
set
{
m_TestValue = value;
}
}

private DateTime m_TestDateTime = DateTime.Now;
public DateTime TestDateTime
{
get
{
return m_TestDateTime;
}
set
{
m_TestDateTime = value;
}
}
}

 

接下来就可以使用对象的Save和Load方法保存和读取Cookies:


保存 

Save方法有两个重载,不带参数的Save方法表示Cookies的过期时间与浏览器相同,即浏览器关闭则Cookies消失。否则需要传入Cookies过期时间。


MyCookieInfo testCookies = new MyCookieInfo();
testCookies.Pkid = 1;
testCookies.TestValue = "中文测试";
testCookies.Save(); 



读取 

MyCookieInfo testCookies = new MyCookieInfo();
testCookies.Load();
this.lblMsg.Text = "Pkid:" + testCookies.Pkid.ToString();
this.lblMsg.Text += ",TestValue:" + testCookies.TestValue.ToString();
this.lblMsg.Text += ",TestDateTime:" +
testCookies.TestDateTime.ToString("yyyy/MM/dd HH:mm:ss",
System.Globalization.DateTimeFormatInfo.InvariantInfo);


现在我们已经可以将一个强类型的对象读取和保存Cookies了。

接下来就可以使用对象的Save和Load方法保存和读取Cookies:


保存 

Save方法有两个重载,不带参数的Save方法表示Cookies的过期时间与浏览器相同,即浏览器关闭则Cookies消失。否则需要传入Cookies过期时间。


MyCookieInfo testCookies = new MyCookieInfo();
testCookies.Pkid = 1;
testCookies.TestValue = "中文测试";
testCookies.Save(); 



读取 

MyCookieInfo testCookies = new MyCookieInfo();
testCookies.Load();
this.lblMsg.Text = "Pkid:" + testCookies.Pkid.ToString();
this.lblMsg.Text += ",TestValue:" + testCookies.TestValue.ToString();
this.lblMsg.Text += ",TestDateTime:" +
testCookies.TestDateTime.ToString("yyyy/MM/dd HH:mm:ss",
System.Globalization.DateTimeFormatInfo.InvariantInfo);


现在我们已经可以将一个强类型的对象读取和保存Cookies了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: