3

I am testing to see whether the user has cookies turned on and I don't seem to be doing something right.

Here is my test:

private bool CookiesAllowed()
{
  var testCookie = new HttpCookie("TestCookie", "abcd");
  System.Web.HttpContext.Current.Response.Cookies.Set(testCookie);

  var tst = System.Web.HttpContext.Current.Request.Cookies.Get("TestCookie");
  if (tst == null || tst.Value == null)
  {
    return false;
  }
  return true;
}

I'm putting a cookie out there... and then getting it back. But it always succeeds.

Here is how I'm disabling them:

enter image description here

I go to Gmail and it tells me my cookies are disabled so I believe I am doing that part right.

What am I doing wrong?

EDIT

To answer James' question, I am calling this from my logon screen, which is my entry screen as the first check:

   public ActionResult LogOn(string id)
    {
      if (!CookiesAllowed())
      {
        return View("CookiesNotEnabled");
      }

Also, I have tested this live, outside of visual studio and not at localhost and it did the same thing.

ErocM
  • 4,505
  • 24
  • 94
  • 161
  • Where are you calling this code? – James Dec 27 '12 at 22:42
  • Perhaps you should take a look at [Best way to determine if cookies are enabled in ASP.NET?](http://stackoverflow.com/questions/210321/best-way-to-determine-if-cookies-are-enabled-in-asp-net) – Cᴏʀʏ Dec 27 '12 at 22:56

1 Answers1

2

You have to let your client/browser do a new Request in order to see if you get the cookie back. When you add a Cookie to the response object, you can only check the presence of it in subsequent new Requests.

Here's a way to do it within the same page in ASP.NET WebForms (since I saw your edit indicating you are using MVC):

private bool IsCookiesAllowed()
{
  string currentUrl = Request.RawUrl;

  if (Request.QueryString["cookieCheck"] == null)
  {
    try
    {
      var testCookie = new HttpCookie("SupportCookies", "true");
      testCookie.Expires = DateTime.Now.AddDays(1);
      Response.Cookies.Add(testCookie);

      if (currentUrl.IndexOf("?", StringComparison.Ordinal) > 0)
        currentUrl = currentUrl + "&cookieCheck=true";
      else
        currentUrl = currentUrl + "?cookieCheck=true";

      Response.Redirect(currentUrl);
    }
    catch
    {
    }
  }

  return Request.Cookies.Get("SupportCookies") != null;
}

This code snippet is inspired by this thread.

Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164
  • This code looks suspiciously similar to [this answer](http://forums.asp.net/t/1044823.aspx) - if so you should cite the source – James Dec 28 '12 at 00:52