在我的注册HttpPost
方法中
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
string ret=WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
if (WebSecurity.Login(model.UserName, model.Password))
{}
}
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
return View(model);
}
无论我用什么用户名注册,我总是得到一个异常,指出“该名称已被使用。请选择另一个用户名”。错误发生在string ret=WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
它将用户名和密码添加到我的 DBtable 中,但之后立即引发异常。
[更新]我RegisterModel
长这样
public class RegisterModel
{
[Required]
[Remote("IsUserAvailable", "UserExistsValidation")]
[Display(Name = "User name")]
[StringLength(30,MinimumLength=2)]
public string UserName { get; set; }
}
和IsUserAvailable
方法UserExistsValidationControler
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class UserExistsValidationControler: Controller
{
public JsonResult IsUserAvailable(string username)
{
if (!WebSecurity.UserExists(username))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
string suggestedUsername = string.Format(CultureInfo.InvariantCulture, "'{0}' is not available", username);
for (int i = 0; i < 100; i++)
{
string candidate = username + i.ToString();
if (!WebSecurity.UserExists(candidate))
{
suggestedUsername = string.Format(CultureInfo.InvariantCulture, "'{0}' is not available. Try {1}.", username, candidate);
break;
}
}
return Json(suggestedUsername, JsonRequestBehavior.AllowGet);
}
}