是的。您可以删除管理员输入的硬编码密码,并将创建用户的调用替换为 var result = await UserManager.CreateAsync(user); 此时不提供密码。确保在创建时向用户发送一封邮件以确认电子邮件。这是example。
在confirmEmail 操作视图中,您可以创建密码设置表单并返回到confirmEmail。示例如下:
HTTP 获取 ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var confirmed = await UserManager.IsEmailConfirmedAsync(userId);
if(confirmed)
{
return await RedirectToDashboard(userId);
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
ViewBag.userId = userId;
ViewBag.code = code;
}
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
您设置的密码表单中的 HTTP POST 到 ConfirmEmail:
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(SetPasswordViewModel model, string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.AddPasswordAsync(userId, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(userId);
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return await RedirectToDashboard(userId);
}
ViewBag.userId = userId;
ViewBag.code = code;
AddErrors(result);
return View(model);
}
要放入 ConfirmEmailView 的示例表单
@using (Html.BeginForm("ConfirmEmail", "Account", new { userId = ViewBag.userId, code = ViewBag.code }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary("", new { @class = "color_orange" })
@Html.PasswordFor(m => m.NewPassword, new { @class = "form-control", placeholder = "New Password" })
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control", placeholder = "Confirm Password" })
<input type="submit" value="Set password" class="btn" />
}
记得给你的confirmEmail视图添加一个模型@model [ProjectName].Models.SetPasswordViewModel
并创建 SetPasswordViewModel:
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}