cookie保存用户名和密码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
A 中使用Cookie保存用户名和密码(转)
上一篇/ 下一篇2010-11-09 17:36:03 / 个人分类:.net开发技术
查看( 120 ) / 评论( 0 ) / 评分( 0 / 0 )
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 {
///
/// 获得Cookie
///
///
///
public static HttpCookie GetCookie(string cookieName)
{
HttpRequest request = HttpContext.Current.Request;
if (request != null) return request.Cookies[cookieName]; return null;
}
///
/// 添加Cookie
///
///
public static void AddCookie(HttpCookie cookie)
{
HttpResponse response = HttpContext.Current.Response;
if (response != null)
{
//指定客户端脚本是否可以访问[默认为false]
cookie.HttpOnly = true;
//指定统一的Path,比便能通存通取
cookie.Path = "/";
//设置跨域,这样在其它二级域名下就都可以访问到了//
cookie.Domain = ""; response.AppendCookie(cookie);
}
}
///
///
///
///
///
public static void SetCookie(string cookieName, string key, string value)
{ SetCookie(cookieName, key, value, null); }
///
///
///
///
///
///
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天