ASP.NET中使用Cookie儲存使用者名稱和密碼 (轉)

iDotNetSpace發表於2010-11-09

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 = "chinesecoo.com"; response.AppendCookie(cookie);

     }

   }

  ///

/// 設定Cookie子鍵的值 

  ///

  ///

  ///  

  ///  

  public static void SetCookie(string cookieName, string key, string value) 

   { SetCookie(cookieName, key, value, null); }

  ///

/// 設定Cookie 

  ///  

  ///

  ///  

  ///  

  ///

  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天 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-677816/,如需轉載,請註明出處,否則將追究法律責任。

相關文章