User.Identity.GetUserId() 返回 null。

5

当我使用User.Identity.GetUserId()方法时,它返回null。我正在尝试创建一个基于MVC的AccountController的方法来更改用户密码。问题出在User.Identity.GetUserId()返回null。

请查看我的控制器,如果您能帮忙就好了。

开始和构造函数

protected ApplicationDbContext ApplicationDbContext { get; set; }
    protected UserManager<ApplicationUser> UserManager { get; set; }

    public ClienteController()
    {
        this.ApplicationDbContext = new ApplicationDbContext();
        this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
        //this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
    }

登录方法

[HttpPost]
    [AllowAnonymous]
    public ActionResult Login(ClienteViewModel model, string returnUrl)
    {
        Cliente cliente = ChecarAcesso(model);

        if (cliente != null)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, cliente.nomeCompletoCliente));
            claims.Add(new Claim(ClaimTypes.Email, cliente.emailCliente));

            var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

            var ctx = Request.GetOwinContext();

            var authenticationManager = ctx.Authentication;
            authenticationManager.SignOut();
            authenticationManager.SignIn(id);
            Session.Add("cliente", cliente);

            if (returnUrl != null)
            {
                if (Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
        }
        else
        {
            return RedirectToAction("AcessoNegado");
        }
    }

无法正常工作的管理方法

[HttpPost]
    [Authorize]
    //[ValidateAntiForgeryToken]
    public async Task<ActionResult> Gerenciar(GerenciarClienteViewModel model)
    {
        //bool hasPassword = HasPassword();
        //ViewBag.HasLocalPassword = hasPassword;
        ViewBag.ReturnUrl = Url.Action("Gerenciar");
        //if (hasPassword)
        //{
            if (ModelState.IsValid)
            {
                string x = User.Identity.GetUserId();
                IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.senhaAntiga, model.novaSenha);
                if (result.Succeeded)
                {
                    return RedirectToAction("Gerenciar", new { Message = ManageMessageId.ChangePasswordSuccess });
                }
                else
                {
                    AddErrors(result);
                }
            }
        //}

        // If we got this far, something failed, redisplay form
        return View(model);
    }

当用户未登录时,User.Identity.GetUserId()返回null。 - A G
是的,但我已经登录了Web应用程序 :/。我已经尝试创建一个新用户并使用它登录。但是,当我尝试更改密码时,该方法会提示UserID为空。 - Paschoali
@ZoranP:真诚地说,我不知道为什么要使用“authenticationManager.SignOut();”。我认为这是一个示例。因此,我注释了那一行,但问题仍然存在。 - Paschoali
你能给我们展示一下你的 Startup.Auth.cs 文件吗?我唯一能想到的是你的 Owin 上下文出了问题... - Zoran P.
虽然说实话,我不确定 GetUserId 是否与 Claims 兼容... 每次我使用它时,我都使用 SignInManager.PasswordSignInAsync,而在使用 Claims 时,我会以不同的方式获取属性。 - Zoran P.
显示剩余2条评论
2个回答

1
我找到了适合我的方法。我使用会话获取用户ID,但我发现ChangePasswordAsync()方法试图在数据库上创建新表。在我的情况下,我已经有一个数据库。因此我只需创建一个方法,该方法接收包含用户ID的会话并通过新密码更改旧密码。这样更简单,而且它可以正常工作。
感谢您的所有帮助。

0

我知道你已经接受了一个答案,但是几个月前我也遇到了这个问题,结果发现在最新版本的MVC中需要稍微做一些不同的处理。

var id = WebSecurity.GetUserId(User.Identity.Name);

为什么我们在ASP.NET MVC应用程序中必须包含WebMatrix.WebData? - NoWar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接