MVC4 - during the action of the postcontroller WebSecurity.CurrentUserId loses value and becomes -1

Somehow, in this controller, after SaveChanges, CurrentUserId becomes -1. Data mail works, and CurrentUserId has a registered value (Example 8888), but after inserting SQL WebSecurity.CurrentUserId becomes -1. Any clue? During debugging, I cannot find where and why.

// POST: /Account/Edit [HttpPost] [ValidateInput(false)] public ActionResult Edit(UserProfile model) { if (ModelState.IsValid) { using (var context = new dbContext()) { var id = WebSecurity.CurrentUserId; var account = context.UserProfiles.Find(id); UpdateModel(account); context.SaveChanges(); return RedirectToAction("Index", "Account"); } } else { return View(model); } } 
+4
source share
1 answer

which will always return -1, you need the code below

  int currentuserid = WebSecurity.GetUserId(username); 

You can then verify that the user ID above matches the user ID in the model to prevent users from changing the code of other users.

as an extra. I use this in my base controller:

 public int GetUserId() { var userid = "0"; if (Request.IsAuthenticated && User.Identity.Name != null) { var membershipUser = Membership.GetUser(User.Identity.Name); if (membershipUser != null) { if (membershipUser.ProviderUserKey != null) { userid = membershipUser.ProviderUserKey.ToString(); } } } return Convert.ToInt32(userid); } 
0
source

Source: https://habr.com/ru/post/1501680/


All Articles