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

标签 c# asp.net asp.net-mvc cookies shopping-cart

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

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

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

最佳答案

我使用 cookie 和数据库做了类似的事情。因此,在 c# 中,您可以有一个 Basket 表,并且在该表中有一个 UserId 列和一个 ProductId 列。然后从您的 Controller 中,您将拉出用户篮,其中 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);

然后在 Controller 中获取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。

关于c# - 如何给匿名用户一个 ID 以记住他们在数据库中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47752909/

相关文章:

C# 复选框 - 我可以清理它吗?

c# - Xamarin 和 Google map 上的距离不同

c# - 将 WCF Ria 服务应用程序部署到 IIS6 时遇到问题 - EndpointNotFoundException 服务 Web-AuthenticationService.svc 不存在

asp.net-mvc - ASP.NET MVC2 和日期时间格式

javascript - 在动态添加的表行中丢失 css 样式

c# - LINQ to XML 新手问题 : Returning More Than One Result

c# - 如何删除azure移动服务中的特定记录

c# - 类库中的 app.config - asp.net C#

asp.net - iis7中的windows身份验证

asp.net - 覆盖 3.8 中 nopcommerce 插件的默认方法路由