将这个cookie检查可靠的检测,如果用户接受Cookie? [英] Will this Cookie Checker reliably detect if user is accepting cookies?

查看:111
本文介绍了将这个cookie检查可靠的检测,如果用户接受Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的网页上设置用户的cookie,以便跟踪时,如果他们回来,会保持其独特的访问者ID在数据库中。我想避免对不接受cookies(如机器人和爬虫),用户在创建的cookie记录,所以我需要一种方法来检查自己是否接受cookie与否。我设计了以下code。

I want my page to set cookies on users in order to track when and if they return, and will be keeping their unique visitor id in a database. I want to avoid creating cookie records for users which do not accept cookies (such as bots and crawlers), so I need a way to check if they are accepting cookies or not. I've devised the following code.

private bool CookiesAreEnabled()
{
    bool result = false;

    HttpCookie CookieChecker = new HttpCookie("CookieChecker");
    CookieChecker.Value = "Do you see me?";
    CookieChecker.Expires = DateTime.Now.AddSeconds(10.0d);
    Response.Cookies.Set(CookieChecker);

    CookieChecker = new HttpCookie("CookieChecker");
    CookieChecker = Request.Cookies["CookieChecker"];
    if (CookieChecker != null)
    {
        result = true;
        CookieChecker = new HttpCookie("CookieChecker");
        CookieChecker.Value = "";
        CookieChecker.Expires = DateTime.Now;
        Response.Cookies.Set(CookieChecker);
    }

    return result;
}

在我看来,这应该检测出禁用cookie,但是它没有!在我的测试,到目前为止,使用Firefox与饼干关闭,code报告启用了Cookie!难道我就找错了树,如果启用了Cookie检测?还是我制作牛逼式的错误呢?

It seems to me that this should detect that cookies are disabled, but it doesn't! In my testing so far using Firefox with cookies turned off, the code reports that cookies are enabled! Am I barking up the wrong tree as far as detecting if cookies are enabled? Or am I making a newby-style mistake?

推荐答案

如果您希望使用计算策略的唯一方法是使用2个要求:首先您设置一个cookie,你读它的第二位。你不能只有一个要求做到这一点。

if you want to use that approch the only way is to use 2 request: the first you set a cookie, the second you read it. You cannot do it with only one request.

否则,我认为你可以用JavaScript实现它(这是一个伪code):

Otherwise I think you can achieve it with javascript (this is a pseudo code):

/*first you check if there is already a cookie with the identifier*/
if(document.cookie.indexOf('cookiewithuniqueidentifier') == -1) {   
    document.cookie = 'testcookie';
    cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
    if (cookieEnabled) { 
        /*ajax request to the server for requesting an unique identifier*/
        /*save a cookie with that identifier*/
        document.cookie='cookiewithuniqueidentifier=936DA01F-9ABD-4d9d-80C7-02AF85C822A8'
    }
}

这篇关于将这个cookie检查可靠的检测,如果用户接受Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆