title: ASP.NET Set cookie ONLY if empty Value
body: <p>I am trying to set a cookie when the user access my webpage. The value of the cookie is a unique number that I store on my database to keep track of when the user comes back to my website. I set the cookie in my global.asax as follow:</p>
  
  <pre><code>void Application_BeginRequest()
  {
      string cookievalue = "";
      string a = "";
      try
      {
          a = GetCookie();
          if (!string.IsNullOrEmpty(a))
          {
              cookievalue = a;
          }
          else
          {
              cookievalue = SetCookie();
          }
      }
      catch (Exception ex)
      {
  
      }
  }
  </code></pre>
  
  <p>In BeginRequest() I only want to check if the cookie exist. If exist, then do nothing and keep the value that is already inside the cookie. If it doesn't exist, then set the cookie and add a value.</p>
  
  <pre><code>public static string GetCookie()
  {
      string cookievalue = "";
      try
      {
          if (HttpContext.Current.Request.Cookies["TestCookie"] != null)
              cookievalue = HttpContext.Current.Response.Cookies["TestCookie"].Value;
      }
      catch (Exception ex)
      {
          //
      }
  
      return cookievalue;
  }
  public static string SetCookie()
  {
      string cookievalue = "";
      try
      {
          HttpCookie myCookie = new HttpCookie("TestCookie");
          // Set the cookie value.
          myCookie.Value = "1234"; //1234 is my unique number
          myCookie.Expires = DateTime.Now.AddYears(50);
          HttpContext.Current.Response.Cookies.Add(myCookie);
          cookievalue = id;
      }
      catch (Exception ex)
      {
          //
      } 
      return cookievalue;
  }
  </code></pre>
  
  <p>The problem is that everytime I reload the page, "TestCookie" gets rewritten with a new value. I have been reading the MSDN about how cookies are stored in ASP.NET and according to the instructions, the way it is supposed to work fine. I must be doing something wrong that I cannot see it. I had all this code inside a normal page e.g. test.aspx.cs to test it early but had the same result and decided to move it to the application level and see if that would make any difference but it did not :(. </p>