Reputation: 4415
I have a requirement where I need to create a database record at the start of a user session on my MVC 4 web site.
The outline of the entry point controller looks like this:
public ActionResult Index(int userId, int requestId) {
var userInfo = db.GetUserInfo(userId, requestId);
if (userInfo == null) {
userInfo = db.CreateUserInfo(userId, requestId);
}
// rest of code
}
What I have found is that this code is not fully reliable in as much that very ocassionaly a duplicate record is created (typically with the same creation date - at least to the nearest millisecond). I can only assume that the (external) web page/client generates two, almost simultaneous, requests.
Note, if a user returns to the site at a later date (using the same query string parameters), then I want them to pick up the existing userInfo record.
I know I could 'fix' the problem by adding a unique index to the table, which I probably need to do anyway, but I would like to know if there is a better pattern to follow?
Upvotes: 0
Views: 167
Reputation: 9458
Generate a random string for the user session when he will register and store it in the userInfo
table in your database. When the user will come to the site at a later date , you will just check the username and password for authentication and if it is successful, then you will get that previously stored unique random string from the database for that user and put it in the session. This way you can use the same random string throughout the lifetime off user. hope this helps
Upvotes: 2