ASP.NET Web Pages - Forgot Password

[ This is an 8 part tutorial, previous tutorial: Login Page ]

In the ForgotPassword page add the following piece of code:

Sponsored Links
@{
    
 
var message = "";
 
if (IsPost)
{
AntiForgery.Validate();
    
var UserName = Request["UserName"];
 
 
Validation.Add("UserName",
Validator.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", "Your username should be an email address"),
Validator.Required()
);

Similar to the previous examples we request the values from HTML elements and validate the data.

if (Validation.IsValid())
{
    
if (WebSecurity.UserExists(UserName))
{
var resetToken = WebSecurity.GeneratePasswordResetToken(UserName, 30);
 
var resetMessage = "You requested a password reset token please following this link to reset your password: " + 
Request.Url.GetLeftPart(UriPartial.Authority) + "/account/resetpassword?token=" + resetToken;
 
try
{
    WebMail.Send(UserName, "Reset Password", resetMessage);
    message = "Please check your email";
}catch (Exception ex)
{
    message = ex.Message;
}
  
} else {
    Validation.AddFormError("The user specified does not exist");
}
 
}
 
}
 
 
}

If the data is valid and the user exists we generate the reset token. The method takes two arguments: username and an optional argument which is used to specify when the token will expire, in this case after 20 minutes. As with the registration page we create a message to send in the email.

HTML

<form method="post">
@AntiForgery.GetHtml()
@Html.ValidationSummary(true)
@message
<fieldset>
<legend>Reset Password</legend>
 
<div>
<label>UserName</label>
<input type="text" name="UserName"/>
@Html.ValidationMessage("UserName")
</div>
 
 
<input type="submit"/>
</fieldset>
 
</form>

[ Continue, Reset Password Page ]