简体   繁体   中英

How to change users password using MVC controller with views using Entity Framework

I have created a controller with views using Entity Framework.Everything works fine but I need to edit users password and I don't have such option,only passwordHash.

How can I do it?

Here is the code of 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);
    }

And here is 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>

If I try the same with model.Password I have a mistake :

The type arguments for method 'System.Web.Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IDictionary)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How can I fix this?Is it somehow connected with absense of field Password in AspNetUsers table and ApplicationUser Model?

您不能,因为没有密码存储,并且正如您所说的,密码哈希也仅存储在数据库中,因此通常的方法是从用户那里检索最后一个密码,然后对其进行哈希处理并将其与存储的哈希进行比较如果它们相等,则可以为用户设置新提供的密码,更简单的方法是使用用户管理器类及其UpdatePassword方法,进一步阅读: https : //msdn.microsoft.com/zh-cn/library/ dn613290%28v = vs.108%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM