CreateAsync asynchronously creates an IdentityUser through UserManager<T>, combining the user object with a password and returning a Task<IdentityResult>. Application code does not manipulate the Identity database context directly. section 38.3.3
Handle the result explicitly:
- Check Succeeded to determine whether the account was created. section 38.3.3
- Redirect to the user list after success. section 38.3.3
- Enumerate Errors and add each Description to ModelState when creation fails, allowing validation messages to appear on the form. section 38.3.3
- Expect password and user-detail validation to reject unsuitable input according to configured IdentityOptions. section 38.3.3
Creating a user from a Razor Page
Bind UserName, Email, and Password properties, configure an IdentityUser from the first two values, then call CreateAsync(user, Password). With Joe, joe@example.com, and Secret123$, successful submission creates the account and redirects to /users/list. section 38.3.3
Listing 38.12 The Create.cshtml file in the Pages/Users folder of the Advanced project
@page
@model CreateModel
<h5 class="bg-primary text-white text-center p-2">Create User</h5>
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label>User Name</label>
<input name="UserName" class="form-control"
value="@Model.UserName" />
</div>
<div class="form-group">
<label>Email</label>
<input name="Email" class="form-control"
value="@Model.Email" />
</div>
<div class="form-group">
<label>Password</label>
<input name="Password" class="form-control"
value="@Model.Password" />
</div>
<div class="py-2">
<button type="submit" class="btn btn-primary">Submit</button>
<a class="btn btn-secondary" asp-page="list">Back</a>
</div>
</form>
@functions {
public class CreateModel : AdminPageModel {
public UserManager<IdentityUser> UserManager;
public CreateModel(UserManager<IdentityUser> usrManager) {
UserManager = usrManager;
}
[BindProperty]
public string UserName { get; set; } = string.Empty;
[BindProperty]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[BindProperty]
public string Password { get; set; } = string.Empty;
public async Task<IActionResult> OnPostAsync() {
if (ModelState.IsValid) {
IdentityUser user =
new IdentityUser {
UserName = UserName,
Email = Email
};
IdentityResult result =
await UserManager.CreateAsync(user, Password);
if (result.Succeeded) {
return RedirectToPage("List");
}
foreach (IdentityError err in result.Errors) {
ModelState.AddModelError("", err.Description);
}
}
return Page();
}
}
}
Inspect the complete Create.cshtml form, including validation summary, bound inputs, submit action, and return link. section 38.3.3
