【发布时间】:2015-05-25 15:32:40
【问题描述】:
当我使用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
-
是的,但我已登录 Web 应用程序:/。我已经测试过创建一个新用户并使用它登录。但是,当我尝试更改密码时,该方法说 UserID 为空。
-
为什么会有“ authenticationManager.SignOut();”?如果删除它会发生什么?
-
@ZoranP.: 说真的,我不知道为什么我有“authenticationManager.SignOut();”。我假设我使用了一个例子。所以,我评论了那行,但仍然遇到同样的问题。
-
你能给我们看看你的 Startup.Auth.cs 文件吗?我唯一能想到的是你的 Owin 上下文有问题......
标签: c# asp.net asp.net-mvc authentication