private void SetUpCookies() {
//记住用户名密码
if (!string.IsNullOrEmpty(Request["remUsername"]))
{
string uName = this.txtName.Text.Trim();
string uPwd = this.txtPwd.Text.Trim();
HttpCookie Cookie = CookiesHelper.GetCookie("UserInfo");
if (Cookie == null)
{
Cookie = new HttpCookie("UserInfo");
Cookie.Values.Add("uName", uName);
Cookie.Values.Add("uPwd", uPwd);
//设置Cookie过期时间
Cookie.Expires = DateTime.Now.AddDays(30);
CookiesHelper.AddCookie(Cookie);
}
else if (!Cookie.Values["uName"].Equals(uName) && !Cookie.Values["uPwd"].Equals(uPwd))
{
CookiesHelper.SetCookie("UserInfo", "uName", uName);
CookiesHelper.SetCookie("UserInfo", "uPwd", uPwd);
}
}
}
private class CookiesHelper {
/// <summary>
/// 获得Cookie
/// </summary>
/// <param name="cookieName"></param>
/// <returns></returns>
public static HttpCookie GetCookie(string cookieName)
{
HttpRequest request = HttpContext.Current.Request;
if (request != null) return request.Cookies[cookieName]; return null;
}
/// <summary>
/// 添加Cookie
/// </summary>
/// <param name="cookie"></param>
public static void AddCookie(HttpCookie cookie)
{
HttpResponse response = HttpContext.Current.Response;
if (response != null)
{
//指定客户端脚本是否可以访问[默认为false]
cookie.HttpOnly = true;
//指定统一的Path,比便能通存通取
cookie.Path = "/";
//设置跨域,这样在其它二级域名下就都可以访问到了 //
cookie.Domain = "chinesecoo.com"; response.AppendCookie(cookie);
}
}
/// <summary> /// 设置Cookie子键的值
/// </summary>
/// <param name="cookieName"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetCookie(string cookieName, string key, string value)
{ SetCookie(cookieName, key, value, null); }
/// <summary> /// 设置Cookie
/// </summary>
/// <param name="cookieName"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expires"></param>
public static void SetCookie(string cookieName, string key, string value, DateTime? expires)
{
HttpResponse response = HttpContext.Current.Response;
if (response != null)
{
HttpCookie cookie = response.Cookies[cookieName];
if (cookie != null)
{
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
cookie.Values.Set(key, value);
else if (!string.IsNullOrEmpty(value))
cookie.Value = value;
if (expires != null)
cookie.Expires = expires.Value;
response.SetCookie(cookie);
}
}
}
}
cookie.Expires=DateTime.Now.AddDays(30);//失效时间为30天