Current Environment Visual Studio 2015, MVC5, Asp.net Identity 2.0, Entity Framework 6.0
I was trying to get User.Identity.GetUserId() after user is just authenticated, but got "Object reference not set to an instance of an object" in the browser.
If it is possible, I want to User.Identity.GetUserID() at the same position. And I wander where the start point is that I can access User.Identity.GetUserId() in the project.
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
string userID = User.Identity.GetUserId().ToString();
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 78: // To enable password failures to trigger account lockout, change to shouldLockout: true Line 79: var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); Line 80: string userID = User.Identity.GetUserId().ToString(); Line 81: switch (result) Line 82: {
You cannot get current user id just after login at least one new request must be made from the user to login takes effect. So if you want the signed in user id just after calling SignIn
method you must use user manager to get the ID instead of using User.Identity.GetUserId()
method.
var user = await UserManager.FindByNameAsync(model.Email);
var userId = user.Id;