ASP.NET Web Pages – Logout and Change Password Page

[ This is an 8 part tutorial, previous tutorial: Reset Password ]

Logout

In the Logout page add the following:

@{
    WebSecurity.Logout();
    Response.Redirect("~/account/login");
}

This is not very difficult: it will log the user out and redirect them to the login page. You can choose to redirect to the home page if you wish.

Change Password Page

In the Change Password page add the following:

@{
   
   
var message = "";
 
 
if (IsPost)
{
    
    AntiForgery.Validate();
 
    var currentPassword = Request["currentPassword"];
    var Password = Request["Password"];
    var ConfirmPassword = Request["ConfirmPassword"];
 
 
    //VALIDATION
    Validation.RequireFields("currentPassword", "Password", "ConfirmPassword");
 
    Validation.Add("Password",
    Validator.StringLength(16, 6)
    );
 
    if (ConfirmPassword != Password)
    {
 
    Validation.AddFormError("Sorry passwords do not match");
 
    }
Similar to the previous pages get user submitted data and validated it. 
    if (Validation.IsValid())
    {
        if (WebSecurity.ChangePassword(WebSecurity.CurrentUserName, currentPassword, Password))
        {
            message= "Password has been changed";
        } else {
            Validation.AddFormError("Current password is wrong");
        }
 
    }
 
}

If the data is valid change the password. It takes 3 arguments: username (which is the current logged in user), current password and new password.

HTML

<form method="post">
@AntiForgery.GetHtml()
<fieldset>
 
<legend>Register</legend>
@Html.ValidationSummary(true)
<div>@message</div>
 
 
<div>
<label>Current Password</label>
<input type="password" name="currentPassword" />
@Html.ValidationMessage("currentPassword")
</div>
 
<div>
<label>Password</label>
<input type="password" name="Password" />
@Html.ValidationMessage("Password")
</div>
 
 
<div>
<label>Confirm Password</label>
<input type="password" name="ConfirmPassword" />
@Html.ValidationMessage("ConfirmPassword")
</div>
 
<input type="submit" value="Change Password"/>
 
</fieldset>
 
 
</form>

[ Continue, Account Management ]