MVC 4 SimpleMembership - Why WebSecurity.CurrentUserId -1 After Login

I am trying to set a cookie at login and have problems getting the current user ID after login. In the example below, intUserId is -1, and WebSecurity.IsAuthenticated is false. Wrong place to put this code? After that, it redirects to the home page ... so I'm not sure why this is not the right place.

// POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) { //TODO: set current company and facility based on those this user has access to int intUserId = WebSecurity.GetUserId(User.Identity.Name); int intUserId2 = WebSecurity.GetUserId(model.UserName); UserSessionPreferences.CurrentCompanyId = 1; UserSessionPreferences.CurrentFacilityId = 1; return RedirectToLocal(returnUrl); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "The user name or password provided is incorrect."); return View(model); } 
+8
asp.net-mvc simplemembership
source share
1 answer

Authorization only sets an authentication cookie.

The asp.net authentication method is to read the cookie in order to authenticate the request, but since the cookie did not exist when the login page was launched, the infrastructure does not know anything about the user.

Reload the page and you will find information about it.

FYI, this is nothing new in SimpleMembership or WebSecurity, as forms authentication has always worked.

+8
source share

All Articles