C# 我的cookie测试不是';行不通
我正在测试用户是否打开了cookies,而我似乎做得不对 这是我的测试:C# 我的cookie测试不是';行不通,c#,asp.net,cookies,C#,Asp.net,Cookies,我正在测试用户是否打开了cookies,而我似乎做得不对 这是我的测试: private bool CookiesAllowed() { var testCookie = new HttpCookie("TestCookie", "abcd"); System.Web.HttpContext.Current.Response.Cookies.Set(testCookie); var tst = System.Web.HttpContext.Current.Request.Cooki
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;
}
我在外面放一块饼干。。。然后把它拿回来。但它总是成功的
以下是我禁用它们的方法:
我去Gmail,它告诉我我的cookies被禁用了,所以我相信我做得对
我做错了什么
编辑
为了回答James的问题,我从我的登录屏幕调用此选项,这是我的输入屏幕,作为第一个检查:
public ActionResult LogOn(string id)
{
if (!CookiesAllowed())
{
return View("CookiesNotEnabled");
}
另外,我在visual studio之外而不是在localhost上对此进行了现场测试,它也做了同样的事情。您必须让您的客户端/浏览器执行一个新的请求,以查看您是否恢复了cookie。将Cookie添加到响应对象时,只能在后续的新请求中检查Cookie是否存在 以下是在ASP.NETWebForms的同一页面中执行此操作的方法(因为我看到您的编辑指示您正在使用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;
}