1

我有一个网站,我想使用 cookie 为所有用户(甚至是匿名用户)存储用户记录。然后我可以跟踪他们的行为并向他们展示相关内容,即使他们回来了。

我目前调用用户的方式是使用以下代码。当我测试它时效果很好,但我可以在日志/数据库中看到,它有时会被垃圾邮件(同一个访问者有数百个匿名用户)。这段代码中可能会出现严重错误,所以我很快就得到了很多用户。

任何人都可以看到问题/解决方法吗?

       public SystemUser SystemUser
    {
        get
        {
            if(!HttpContext.Current.Request.Browser.Cookies)
            {
                logger.Info("Users browser did not allow cookies (crawler?)");
                return CreateEmptyUser();
            }
            var user = HttpContext.Current.Session[Constants.Sessions.LoginUser] as SystemUser;

            if(user == null)
            {
                logger.Info("User was null - first page visit");
                var httpCookie = HttpContext.Current.Request.Cookies[Constants.Cookies.AnonymousUser];
                if (httpCookie == null || httpCookie.Value == string.Empty)
                {
                    // totally new user - new anonymous user
                    var userFromId = SetupAnonymousUser();
                    logger.Info("We have a totally new visitor coming to our site. Userid: " + userFromId.UserId);
                }
                else
                {
                    logger.Info("User has been here before, as the anonymous user cookie wasn't null");

                    // anonymousUser - has been there before
                    var anonymousUser = httpCookie.Value;
                    int userid;
                    int.TryParse(anonymousUser, out userid);
                    if(userid > 0)
                    {
                        logger.Info("Getting user from id: " + userid);
                        var userFromId = UserManager.GetUser(userid);

                        if(userFromId != null)
                        {
                            HttpContext.Current.Session[Constants.Sessions.LoginUser] = userFromId;    
                        }
                        else
                        {
                            logger.Error("User has been here before, but couldnt find in database. Anonymous cookie deleted maybe?");
                            SetupAnonymousUser();
                        }

                    }
                    logger.Info("User has been there before: " + userid);
                }
            }
            var initializedUser =  HttpContext.Current.Session[Constants.Sessions.LoginUser] as SystemUser;

            if(initializedUser != null)
            {
                return initializedUser; 
            }
            else
            {
                logger.Info("Creating an empty user as initialized user was null");
                return CreateEmptyUser();
            }
        }
        set { HttpContext.Current.Session[Constants.Sessions.LoginUser] = value; }
    }

还有我们的 SetupAnonymousUser():

    private static SystemUser SetupAnonymousUser()
    {
        int userid = CreateAnonymousUser();

        var newCookie = new HttpCookie(Constants.Cookies.AnonymousUser)
                            {
                                Value = userid.ToString(),
                                Expires = DateTime.Now.AddDays(365)
                            };

        var userFromId = UserManager.GetUser(userid);
        HttpContext.Current.Session[Constants.Sessions.LoginUser] = userFromId;
        HttpContext.Current.Response.Cookies.Add(newCookie);
        return userFromId;
    }

编辑:

这是出现问题的一些日志:

2012-11-04 13:58:40,298 [7] INFO  GKBusiness.Context.SystemContext [(null)] - User was null - first page visit
2012-11-04 13:58:40,313 [7] INFO  GKBusiness.Context.SystemContext [(null)] - Anonymous user created - with user id GKBusiness.Data.SystemUser
2012-11-04 13:58:40,313 [7] INFO  GKBusiness.Context.SystemContext [(null)] - We have a totally new visitor coming to our site. Userid: 4466
2012-11-04 13:58:40,391 [7] INFO  GKBusiness.Context.SystemContext [(null)] - User was null - first page visit
2012-11-04 13:58:40,391 [7] INFO  GKBusiness.Context.SystemContext [(null)] - Anonymous user created - with user id GKBusiness.Data.SystemUser
2012-11-04 13:58:40,391 [7] INFO  GKBusiness.Context.SystemContext [(null)] - We have a totally new visitor coming to our site. Userid: 4467
4

1 回答 1

1

The code itself doesn't look flawed, but there are a few possibilities that might cause the problem you're facing (same user has multiple "anonymous user" entries).

To help pinpoint the problem I recommend adding some more logger.Info references in your code, more specifically when you get a cookie back from the user but for some reason it's malformed:

  1. When (userid <= 0)
  2. When userFromId == null
  3. When initializedUser == null

This way, when you're able to reproduce the problem you can check the logs and see what exactly is causing this problem.

I should also mention that since cookies can be modified by the client, you should consider using a Guid instead of a numeric UserId -this will make it harder for anyone who attempts to "impersonate" another user.

于 2012-11-04T11:08:47.380 回答