如何给匿名用户一个 ID 以记住他们在数据库中的数据?

How to give an ID to an anonymous user to remember their data on database?

我想为打开我的网站并向他们的 "shopping cart" 添加一些项目的用户提供一个 ID,即使他们没有注册该服务。只需添加,然后在他们想要结帐时继续注册。如果他们在添加东西后不去结账,然后关闭他们的浏览器,2 天后回来,我想从数据库中检索他们以前的订单。

如何为用户提供唯一的 ID 并在他们下次访问时记住它?

我想我需要使用 cookie,但不知道具体怎么做?

当用户将东西添加到购物车时,运行 javascript 像这样:

 var storedId = localStorage.getItem('myId');

if(storedId == null)
{
   storedId = parseInt(Math.Random * 1000); // or better, use UUID generation from here: 

   localStorage.setItem('myId', storedId); // for future reference
}

现在,每当您将商品添加到购物车时,post ID,例如

控制器:

[HttpPost]
public ActionResult AddToCard(string userId, string productId, int quantity)
{
  /// perform your saving to db
}

Ajax(或您使用的任何框架):

$.post('/somewhere', {userId: storedId, productId: 'whatever', quantity: 1});

我使用 cookie 和数据库做了类似的事情。因此,在 c# 中,您可以有一个购物篮 table,并且在 table 中有一个 UserId 列和一个 ProductId 列。然后从您的控制器中,您将拉出用户篮,其中 UserId 是数据库中的用户篮。

正在设置 cookie:

string cookieValue = Guid.NewGuid().ToString();
//Creating a cookie which has the name "UserId"
HttpCookie userIdCookie = new HttpCookie("userId");
userIdCookie.Value = cookieValue;
//This is where you would state how long you would want the cookie on the client. In your instance 2 days later.
userIdCookie.Expires = DateTime.Now.AddDays(3);
Response.SetCookie(userIdCookie);

然后在控制器中获取cookie:

public ActionResult Basket()
{
    //Getting the cookie which has the name "userId" and assigning that to a variable.
    string userId =  Request.Cookies.Get("userId").Value;
    var basket = _context.Basket.Where(x => x.UserId == userId);       
    return View(basket);
}

注意:我在这里使用了Request.Cookies.Get("userId"),因为如果你使用Response.Cookies.Get("userId"),并且 cookie "UserId" 不存在,那么它将为您创建 cookie。