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

问题内容:

I want to give an ID to a user that opens my website and adds some items to their “shopping cart”, even if they aren’t signed up to the service. Just add, then proceed to sign up when they want to check out. And if they don’t go to checkout after adding stuff, then close their browser, come back 2 days later, I want to retrieve their previous orders from database.

How do I give this ID that is unique to a user and remember it next time they visit?

I assume I need to use cookies, but don’t know how exactly?

问题评论:

1  
you can use cookies or html5 localstorage
    
Like I said, I assume that I need to use cookies, but how do I use them and how do I use them with asp.net?
– LookingSharp
3 hours ago
    
are you using webforms?
2  
You could try searching google for something like “asp.net using cookies” – top result. You will not usually get a very good response on SO if you don’t show that you have made some effort of your own. Typically you would even show the code you have tried so far & explain why it doesn’t appear to be working. You will get much more help that way.
1  
Consider generating a GUID, and store it in a cookie.

答案:

答案1:

I have done something similar using cookies and a database. So in c# you could have a Basket table, and in that table have a UserId column along with a ProductId column. Then from your controller you would pull the users basket where the UserId is of that in the database.

Setting the 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);

Then to get the cookie in the controller:

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);
}

Note: I have used Request.Cookies.Get(“userId”) here because if you use Response.Cookies.Get(“userId”), and the cookie “UserId” does not exist, then it will create the cookie for you.

答案评论:

    
I already have an “orders” table, which is connected to a “customers” table, I just want to make a temporary customer, and save this temporary customer’s data on a cookie for that customer, that is all.
– LookingSharp
3 hours ago
    
Trying this now, figured out how to do it.
– LookingSharp
2 hours ago
    
It worked perfect after some little tweaks, I added a small condition to get cookie first, and if not any is get, only then assigning a cookie (otherwise it created a new user every time Homepage was opened). Thank you!
– LookingSharp
2 hours ago
    
ah yes sorry. You could just do if(Request.cookies.Get(“userId”) == null) {Response.SetCookie(“myCookie”);}. You could set this in the Products controller get method so when a user hits that page the userId would be assigned. And glad i could help 🙂

答案2:

When the user adds something to cart, run javascript like so:

 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
}

Now, whenever you add something to cart, post the id, e.g.

Controller:

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

Ajax (or whatever framework you use):

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

答案评论:

答案3:

You could use JWT to save a token.
In this token you can save every item the user has put into his cart.
Save the JWT in local storage.
Once the user opens the website again you can send the token to your server.
The server can decrypt the token and see what items where previously put into the shopping cart.

答案评论:

    
This is insane 🙂 first of all, the server is trusting the client, and good luck with stock reservation. second, if the user adds 10K items to the cart, this token will become rather unwieldy.
    
@zaitsman who would put 10k items in their cart? And if you really want to keep it safe you can add the token in your database.

原文地址:

https://stackoverflow.com/questions/47752909/how-to-give-an-id-to-an-anonymous-user-to-remember-their-data-on-database

添加评论