User.Identity.GetUserId () returns null
When I use the method User.Identity.GetUserId()
, it returns null. I am trying to make a method ( AccountController
MVC based ) to change a user's password. The problem is that it User.Identity.GetUserId()
returns null.
Check out my controller and help if you can.
Start and constructor
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));
}
Login method
[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");
}
}
Control method that doesn't work
[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);
}
source to share
I found a way that works for me. I am getting the id of the user using the session, but I found that the method is ChangePasswordAsync()
trying to create a new table in the database. In my case, I already have a database. So I just create a method that gets the session with the user id and changes the old password with the new password. Much easier and works.
Thanks for the help.
source to share