在MVC中处理忘记密码而无需电子邮件确认

时间:2018-03-31 08:44:25

标签: c# asp.net-mvc

如何在没有确认电子邮件的情况下处理用户在ASP.NET MVC 5中忘记密码?

我尝试了这种方法:http://www.dominikgorecki.com/2014/01/implementing-password-reset-in-mvc-4-ef-code-first-using-simple-membership-part-2/。但是当我提交电子邮件时,我会注意到“该电子邮件找不到用户。”

控制器代码(AccountController.cs)

// GET: Account/LostPassword
[AllowAnonymous]
public ActionResult LostPassword()
{
    return View();
}

// POST: Account/LostPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LostPassword(LostPasswordModel model)
{
    if (ModelState.IsValid)
    {
        MembershipUser user;
        var context = new ApplicationDbContext();
        {
            var foundUserName = (from u in context.Users
                                 where u.Email == model.Email
                                 select u.UserName).FirstOrDefault();
            if (foundUserName != null)
            {
                user = Membership.GetUser(foundUserName.ToString());
            }
            else
            {
                user = null;
            }
        }
        if (user != null)
        {
            // Generae password token that will be used in the email link to authenticate user
            var token = WebSecurity.GeneratePasswordResetToken(user.UserName);
            // Generate the html link sent via email
            string resetLink = "<a href='"
               + Url.Action("ResetPassword", "Account", new { rt = token }, "http")
               + "'>Reset Password Link</a>";

            // Email stuff
            string subject = "Reset your password for asdf.com";
            string body = "You link: " + resetLink;
            string from = "donotreply@asdf.com";

            MailMessage message = new MailMessage(from, model.Email);
            message.Subject = subject;
            message.Body = body;
            SmtpClient client = new SmtpClient();

            // Attempt to send the email
            try
            {
                client.Send(message);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Issue sending email: " + e.Message);
            }
        }
        else // Email not found
        {
            /* Note: You may not want to provide the following information
            * since it gives an intruder information as to whether a
            * certain email address is registered with this website or not.
            * If you're really concerned about privacy, you may want to
            * forward to the same "Success" page regardless whether an
            * user was found or not. This is only for illustration purposes.
            */
            ModelState.AddModelError("", "No user found by that email.");
        }
    }

    /* You may want to send the user to a "Success" page upon the successful
    * sending of the reset email link. Right now, if we are 100% successful
    * nothing happens on the page. :P
    */
    return View(model);
}
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string rt)
{
    ResetPasswordModel model = new ResetPasswordModel();
    model.ReturnToken = rt;
    return View(model);
}

// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordModel model)
{
    if (ModelState.IsValid)
    {
        bool resetResponse = WebSecurity.ResetPassword(model.ReturnToken, model.Password);
        if (resetResponse)
        {
            ViewBag.Message = "Successfully Changed";
        }
        else
        {
            ViewBag.Message = "Something went horribly wrong!";
        }
    }
    return View(model);
}

型号代码(AccountViewModel.cs)

public class LostPasswordModel
{
    [Required(ErrorMessage = "We need your email to send you a reset link!")]
    [Display(Name = "Your account email")]
    [EmailAddress(ErrorMessage = "Not a valid email--what are you trying to do here?")]
    public string Email { get; set; }
}

public class ResetPasswordModel
{
    [Required]
    [Display(Name = "New Password")]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Required]
    [Display(Name = "Confirm Password")]
    [DataType(DataType.Password)]
    [Compare("Password", ErrorMessage = "New password and confirmation does not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    public string ReturnToken { get; set; }
}

查看代码(LostPassword.cshatml)

    @model AppZillafy.Models.LostPasswordModel
@{
    ViewBag.Title = "Lost Password";
}

<h2>Lost Password</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <fieldset>
        <legend>Lost Password Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)
            </li>
        </ol>
        <input type="submit" value="Recover Account" />
    </fieldset>
}

查看代码(ResetPassword.cshatml)

@model AppZillafy.Models.ResetPasswordModel

@{
    ViewBag.Title = "ResetPassword";
}

<h2>Reset Password</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Resetting password form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
            @Html.HiddenFor(m => m.ReturnToken)
        </ol>
        <input type="submit" value="Reset" />
    </fieldset>
    <h2>@ViewBag.Message</h2>
}

0 个答案:

没有答案