User.Identity.GetUserId() returns null
本文关键字:returns null Identity GetUserId User | 更新日期: 2023-09-27 17:50:44
当我使用User.Identity.GetUserId()
方法时,它返回null。我试图使一种方法(基于MVC的AccountController
)改变用户的密码。问题是User.Identity.GetUserId()
返回null。
看看我的控制器,如果可以的话帮帮忙。
Begin和构造函数
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);
}
标题>
我找到了一个适合我的方法。我使用session获取用户的ID,但是我发现ChangePasswordAsync()
方法试图在数据库上创建一个新表。在我的例子中,我已经有了一个数据库。因此,我只是创建了一个方法来接收带有用户ID的会话,并用新密码更改旧密码。更简单,更有效。
谢谢你的帮助。
我知道你已经接受了一个答案,但是几个月前我遇到了这个问题,结果我需要用最新版本的MVC做一点不同的事情。
var id = WebSecurity.GetUserId(User.Identity.Name);