Cannot access User.Identity.GetUserId() inside Login action of AccountController in MVC 5

旧街凉风 提交于 2020-01-07 02:26:04

问题


Current Environment Visual Studio 2015, MVC5, Asp.net Identity 2.0, Entity Framework 6.0

Problem

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.

Expectation

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.

Code

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

Error In Browser

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: {


回答1:


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;



回答2:


try use the current code instead

System.Web.HttpContext.Current.User.Identity.GetUserId();


来源:https://stackoverflow.com/questions/36032735/cannot-access-user-identity-getuserid-inside-login-action-of-accountcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!