如何计算用户的视图?

Jey*_*mov 1 asp.net-mvc-3

我想计算用户观看产品的次数.

Product有整数类型的ViewCount属性,在Details视图中,我增加了ViewCount:

public ActionResult Details( int id )
  {
    ...
    product.ViewCount = product.ViewCount + 1;
    db.SaveChanges();
    return View( product );
  }
Run Code Online (Sandbox Code Playgroud)

但在每次刷新时,ViewCount都会增加.

我应该怎么做,ViewCount在每个用户会话中增加1次?

或其他方式,正确的标签,任何链接,请.

小智 6

你可以使用cookie.

var productId = 1;


if (Request.Cookies["ViewedPage"] != null)
{
    if (Request.Cookies["ViewedPage"][string.Format("pId_{0}",productId )] == null)
    {
        HttpCookie cookie = (HttpCookie)Request.Cookies["ViewedPage"];
        cookie[string.Format("pId_{0}",productId )] = "1";
        cookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(cookie); 

        db.Execute("UPDATE Products SET ViewCount = ViewCount + 1 WHERE ProductId = @id", new { id = productId } ); 
        db.SaveChanges();
    }
}
else
{
    HttpCookie cookie = new HttpCookie("ViewedPage");
    cookie[string.Format("pId_{0}",productId )] = "1";
    cookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(cookie); 

    db.Execute("UPDATE Products SET ViewCount = ViewCount + 1 WHERE ProductId = @id", new { id = productId } ); 
    db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)