C# judge whether cookies are disabled on the client

Lionsure 2020-07-22 Original by the website

For the sake of safety and convenience, some clients have disabled cookies. When cookies are used to save some information(especially some very critical information), it is necessary to judge whether cookies are disabled on the client. How to do?

Since there is no direct judgment method, it can only be judged indirectly. The specific method is to set a Cookie value, and then take it to check, if it can be got, the Cookie is not disabled; otherwise, it is disabled. The specific implementation code is as follows:

 

1. Method of setting cookie value

/// <summary>
       /// Set cookie value
       /// </summary>
       /// <param name="cookieName">Cookie name</param>
       /// <param name="val">Value to be saved</param>
       /// <param name="expireTime">Expiration</param>

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

 

2. Method of getting cookie value

/// <summary>
       /// Get cookie value
       /// </summary>
       /// <param name="cookieName">Cookie name</param>
       /// <return>Expiration</return>

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

 

3. Judge in the page load event

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

       if (GetCookie("isDisable") != string.Empty)
                     Response.Write("Cookies are not disabled!");
              else
                     Response.Write("Cookies have been disabled!");
       }