如果您使用的是开箱即用的模板,您不必担心Username
,WebSecurity
会确保其独一无二。至于Email
,这就是我在我目前正在处理的 Web 应用程序中所做的。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
using (EfDb db = new EfDb())
{
UserProfile userEmail = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
try
{
// Check if email already exists
if (userEmail == null)
{
var token = WebSecurity.CreateUserAndAccount(
model.UserName,
model.Password,
new
{
model.Email
},
true);
}
ModelState.AddModelError("", ErrorCodeToString(MembershipCreateStatus.DuplicateEmail));
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
如您所见,这里的数据库与验证无关。C# 代码负责处理它。只要确保在你的 ViewModel 中你有这个:
[EmailAddress]
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
在视图中
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>