我的cookie测试不起作用

时间:2012-12-27 21:53:00

标签: c# asp.net cookies

我正在测试用户是否已启用Cookie并且我似乎没有做正确的事情。

这是我的测试:

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;
}

我正在把饼干放在那里......然后把它拿回来。但它总是成功。

以下是我禁用它们的方法:

enter image description here

我转到Gmail,它告诉我我的Cookie被禁用,所以我相信我正在做那个部分。

我做错了什么?

修改

要回答詹姆斯的问题,我是从我的登录屏幕调用此问题,这是我的输入屏幕作为第一个检查:

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

另外,我已经在视觉工作室之外测试了这个,而不是在localhost测试,它也做了同样的事情。

1 个答案:

答案 0 :(得分:2)

您必须让您的客户端/浏览器执行新的请求,以查看您是否收到了cookie。向响应对象添加Cookie时,只能检查后续新请求中是否存在Cookie。

这是在ASP.NET WebForms 的同一页面中执行此操作的方法(因为我看到您的编辑指示您正在使用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 thread

相关问题