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

C# 如何给匿名用户一个ID来记住他们在数据库中的数据?,c#,asp.net,asp.net-mvc,cookies,shopping-cart,C#,Asp.net,Asp.net Mvc,Cookies,Shopping Cart,我想给一个用户一个ID,该用户打开我的网站,并将一些项目添加到他们的“购物车”,即使他们没有注册该服务。只需添加,然后在他们想要退房时继续注册。若他们在添加东西后并没有去结帐,那个么关闭浏览器,两天后再回来,我想从数据库中检索他们以前的订单 我如何给这个用户唯一的ID,并在下次访问时记住它 我假设我需要使用cookies,但不知道具体如何使用?当用户向购物车添加内容时,请按如下方式运行javascript: var storedId = localStorage.getItem('myId')

我想给一个用户一个ID,该用户打开我的网站,并将一些项目添加到他们的“购物车”,即使他们没有注册该服务。只需添加,然后在他们想要退房时继续注册。若他们在添加东西后并没有去结帐,那个么关闭浏览器,两天后再回来,我想从数据库中检索他们以前的订单

我如何给这个用户唯一的ID,并在下次访问时记住它


我假设我需要使用cookies,但不知道具体如何使用?

当用户向购物车添加内容时,请按如下方式运行javascript:

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

if(storedId == null)
{
   storedId = parseInt(Math.Random * 1000); // or better, use UUID generation from here: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript

   localStorage.setItem('myId', storedId); // for future reference
}
现在,无论何时向购物车添加内容,都要发布id,例如

控制器:

[HttpPost]
public ActionResult AddToCard(string userId, string productId, int quantity)
{
  /// perform your saving to db
}
Ajax(或您使用的任何框架):


我用cookies和数据库做了类似的事情。因此,在c#中可以有一个Basket表,在该表中有一个UserId列和一个ProductId列。然后从您的控制器中拉出用户篮,其中的用户ID是数据库中的用户ID

设置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

你可以使用Cookie或html5 LocalStorages就像我说的,我假设我需要使用Cookie,但是我如何使用它们以及如何在asp.net中使用它们?你在使用webforms吗?你可以尝试在google中搜索类似“asp.net使用Cookie”的东西。你通常不会得到很好的回应,所以如果你没有表现出你自己的努力。通常,您甚至会显示到目前为止您已经尝试过的代码&解释为什么它看起来不起作用。你会得到更多的帮助。考虑生成一个GUID,并将其存储在cookie中。我已经有一个“订单”表,它连接到一个“客户”表,我只想制作一个临时客户,并把这个临时客户的数据保存在那个客户的cookie上,仅此而已。在做了一些小的调整后,它工作得非常完美,我添加了一个小条件,首先获取cookie,如果没有任何条件,则只分配一个cookie(否则每次打开主页时它都会创建一个新用户)。非常感谢。啊,是的,对不起。如果(Request.cookies.Get(“userId”)==null){Response.SetCookie(“mycokie”);},您可以这样做。您可以在Products controller get方法中设置此选项,以便当用户点击该页面时,将分配用户ID。很高兴我能帮忙:)
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);
}