无法在MVC 5中的AccountController的登录操作中访问User.Identity.GetUserId() [英] Cannot access User.Identity.GetUserId() inside Login action of AccountController in MVC 5

查看:169
本文介绍了无法在MVC 5中的AccountController的登录操作中访问User.Identity.GetUserId()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前环境 Visual Studio 2015,MVC5,Asp.net Identity 2.0,实体框架6.0

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

我只是在对用户进行身份验证之后尝试获取User.Identity.GetUserId(),但是在浏览器中得到了对象引用未设置为对象的实例".

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.

如果可能的话,我想将User.Identity.GetUserID()放在同一位置.我徘徊在哪里可以访问项目中的User.Identity.GetUserId()的起点.

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

浏览器错误

"/"应用程序中的服务器错误. 你调用的对象是空的. 说明:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息.

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.

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

源错误:

第78行://要启用密码失败来触发帐户锁定,请更改为shouldLockout:true 第79行:var result = await SignInManager.PasswordSignInAsync(model.Email,model.Password,model.RememberMe,shouldLockout:false); 第80行:字符串userID = User.Identity.GetUserId().ToString(); 第81行:开关(结果) 第82行:{

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

推荐答案

登录后,您至少无法从用户发出一个新请求,登录才能生效,因此您无法获取当前用户ID.因此,如果要在调用SignIn方法后立即登录的用户ID,则必须使用用户管理器来获取ID,而不要使用User.Identity.GetUserId()方法.

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;

这篇关于无法在MVC 5中的AccountController的登录操作中访问User.Identity.GetUserId()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆