gpt4 book ai didi

c# - User.Identity.GetUserId() 返回 null

转载 作者:行者123 更新时间:2023-11-30 12:43:46 26 4
gpt4 key购买 nike

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

看看我的 Controller ,如果可以的话帮忙。

开始和构造函数

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 的 session 并通过新密码更改旧密码。简单得多,而且有效。

感谢大家的帮助。

关于c# - User.Identity.GetUserId() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30441620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com