public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { while (true) { using (var db = new MKContext()) { var user = db.UserProfiles.Where(u => u.UserName == model.UserName || u.Email == model.Email).FirstOrDefault(); if (user != null) { ViewBag.ErrorMessage = "Email or username is already exist"; ModelState.AddModelError("", ViewBag.ErrorMessage); break; } model.AddUserProfile(db); db.SaveChanges(); } // 尝试注册用户 try { WebSecurity.CreateAccount(model.UserName, model.Password); WebSecurity.Login(model.UserName, model.Password); return(RedirectToAction("Index", "Home")); } catch (MembershipCreateUserException e) { ViewBag.ErrorMessage = ErrorCodeToString(e.StatusCode); ModelState.AddModelError("", ViewBag.ErrorMessage); } } } // 如果我们进行到这一步时某个地方出错,则重新显示表单 return(View(model)); }