C# 判斷客戶端是否禁用Cookie的方法

費勁_奮進發表於2014-04-29
1、設定 Cookie 值 方法

  /// <summary>
  /// 設定 Cookie 值
  /// </summary>
  /// <param name="CookieName">Cookie 名稱</param>
  /// <param name="val">待儲存的值</param>
  /// <param name="expireTime">過期時間</param>

  public void SetCookie(string CookieName, string val, expireTime)
  {
    Response.Cookies[cookieName].Value = val;
    Response.Cookies[cookieName].Expires = DateTime.Now.AddHours(expireTime);
  }


2、獲取 Cookie 值 方法

  /// <summary>
  /// 獲取 Cookie 值
  /// </summary>
  /// <param name="CookieName">Cookie 名稱</param>
  /// <return>過期時間</return>

  public string GetCookie(string CookieName)
  {
    if(Request.Cookies[cookieName] != null)
      return Request.Cookies[cookieName].Value.ToString();
    else
      return string.Empty;
  }


 3、在頁面載入事件中判斷

  protected void Page_Load(object sender, EventArgs e)
  {
    SetCookie("isDisable", "ok", 6);

    if (GetCookie("isDisable") != string.Empty)
      Response.Write("Cookie 沒有被禁用!");
    else
      Response.Write("Cookie 已被禁用!");
  }


相關文章