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:

var message = "";
if (IsPost)
var UserName = Request["UserName"];
Validator.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", "Your username should be an email address"),

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;
    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.


<form method="post">
<legend>Reset Password</legend>
<input type="text" name="UserName"/>
<input type="submit"/>

[ Continue, Reset Password Page ]