c# - 我的 cookie 测试不起作用

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

我在外面放了一个 cookie……然后把它取回来。但它总是成功。

以下是我如何禁用它们:

enter image description here

我转到 Gmail,它告诉我我的 cookie 已被禁用,所以我相信我做对了。

我做错了什么?

编辑

为了回答 James 的问题,我从我的登录屏幕调用它,这是我的第一个检查输入屏幕:

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

此外,我已经在 visual studio 之外而不是在本地主机上进行了现场测试,它做了同样的事情。

最佳答案

你必须让你的客户端/浏览器做一个新的请求,以查看你是否取回了 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 .

关于c# - 我的 cookie 测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14061783/

相关文章:

php - 德鲁帕尔 7 : Access Denied localhost/user/[user_id] after successful login

c# - 有人举例说明如何在 SQL Server 2008 中插入 CLR?

asp.net - mscorlib.dll 中发生类型 'System.StackOverflowException' 的未处理异常

javascript - 当用户使用不同帐户打开新选项卡时,强制刷新旧选项卡中的站点

python - 测试 Django 应用程序 cookie、 session 和状态

ASP.NET 身份数据库第一个自定义用户和角色

c# - "Unknown Node:VarName"XML 反序列化期间

c# - 如何动态或在运行时设置 PropertyGrid 的 DefaultValueAttribute?

c# - 要通过什么?引用对象还是值类型?

asp.net - 如何在运行时打开数据库连接?