When I use User.Identity.GetUserId()
method, it returns null. I am trying to make a method (based on AccountController
of MVC) to change user's password. The problem is with User.Identity.GetUserId()
returning null.
Look my controller and help if you can.
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);
}
I found a way that works for me. I get the ID of user using session, but I discovered that method ChangePasswordAsync()
tries to create a new table on database. In my case, I already have a database. So I just create a method that receives session with user ID and change old password by the new password. Much more simple and it works.
Thank you for all help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With