如何使用MVC控制器和使用实体框架的视图更改用户密码
本文关键字:视图 密码 用户 框架 实体 MVC 何使用 控制器 | 更新日期: 2023-09-27 18:28:06
我使用实体框架创建了一个带有视图的控制器。一切都很好,但我需要编辑用户密码,我没有这样的选项,只有passwordHash。
我该怎么做?
这是UsersController的代码:
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser applicationUser = db.Users.Find(id);
if (applicationUser == null)
{
return HttpNotFound();
}
return View(applicationUser);
}
// POST: Users/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,Password,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
db.Entry(applicationUser).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(applicationUser);
}
这是Edit.shtml:
<div class="form-group">
@Html.LabelFor(model => model.PasswordHash, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PasswordHash, "", new { @class = "text-danger" })
</div>
</div>
如果我在模特身上也尝试同样的方法。密码我有一个错误:
方法的类型参数'System.Web.Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper,System.Linq.Expressions.Expression>,System.Collections.Generic.IDictionary)'不能为根据用法推断。尝试指定类型参数明确地
我该怎么解决这个问题?它是否与AspNetUsers表和ApplicationUser模型中缺少字段Password有某种联系?
你不能,因为没有存储密码,而且正如您所说,只有密码哈希存储在数据库中,所以通常的方法是从用户那里检索最后一个密码,然后对其进行哈希,并将其与存储的哈希进行比较。如果它们相等,则您可以为用户设置新提供的密码。更简单的方法是使用用户管理器类及其UpdatePassword方法进一步阅读:https://msdn.microsoft.com/en-us/library/dn613290%28v=vs.108%29.aspx