Cookies的各方面知识(基础/高级)深度了解(3)

如果我们保存一个Cookies并设置加密,那么在非HTTPS的页面中,无论是使用javascript还是服务器端都无法获得此Cookies。但是在本地依然可以看到此Cookies的存在。

8.Cookies与Ajax

如果Ajax请求访问一个服务器页面,此服务器页面是可以向用户浏览器写入Cookies和Session的。

四. Cookies最佳实践

在了解了Cookies的相关知识后,下面提出最佳的事件方法。其中包括客户端和服务器端两部分。

(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>Cookies过期事件</param>
/// <returns>是否保存成功</returns>
public bool Save()
{
return this.Save(DateTime.MinValue);
}
/// <summary>
/// 保存Cookies,需要指定过期时间。
/// </summary>
/// <param>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();
}
//如果是或多级域名,需要转化为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:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdggz.html