我正在测试以查看用户是否打开了 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……然后把它取回来。但它总是成功。
以下是我如何禁用它们:
我转到 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/