C# 如何远程验证电子邮件或检查电子邮件是否存在
我试图检查注册时是否存在电子邮件,以便数据库中没有重复的电子邮件。我使用MVC4默认Internet应用程序执行此操作,但我已将电子邮件字段添加到RegisterviewModel。我还注意到,用户名字段做得很好,但我不知道他们是如何做到的。我试图关注下面的这个博客,但没有运气,因为当我单击“创建”时没有响应。当我使用firebug时,当执行Json操作时,我得到了C# 如何远程验证电子邮件或检查电子邮件是否存在,c#,asp.net-mvc-4,email-validation,asp.net-4.5,remote-validation,C#,Asp.net Mvc 4,Email Validation,Asp.net 4.5,Remote Validation,我试图检查注册时是否存在电子邮件,以便数据库中没有重复的电子邮件。我使用MVC4默认Internet应用程序执行此操作,但我已将电子邮件字段添加到RegisterviewModel。我还注意到,用户名字段做得很好,但我不知道他们是如何做到的。我试图关注下面的这个博客,但没有运气,因为当我单击“创建”时没有响应。当我使用firebug时,当执行Json操作时,我得到了状态:302 Found 这就是我所拥有的: UserProfile [Table("UserProfile")] public c
状态:302 Found
这就是我所拥有的:
UserProfile
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
注册服务模型
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[Remote("DoesUserEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email address already exists. Please enter a different Email address.")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
注册操作
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try //CreateUserAndAccount
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public JsonResult DoesUserEmailExist(string email)
{
var user = Membership.GetUserNameByEmail(email);
return Json(user == null);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
try
{
// Check if email already exists
if (email == null)
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Json操作
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try //CreateUserAndAccount
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public JsonResult DoesUserEmailExist(string email)
{
var user = Membership.GetUserNameByEmail(email);
return Json(user == null);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
try
{
// Check if email already exists
if (email == null)
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
编辑:添加注册视图
@model Soccer.Models.RegisterModel
@{
ViewBag.Title = "Register";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>Create a new account.</h2>
</hgroup>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@model Soccer.Models.RegisterModel
@{
ViewBag.Title=“寄存器”;
}
@ViewBag.Title。
创建一个新帐户。
@使用(Html.BeginForm()){
@Html.AntiForgeryToken()
@Html.ValidationSummary()
登记表
@LabelFor(m=>m.UserName)
@Html.TextBoxFor(m=>m.UserName)
@LabelFor(m=>m.Email)
@Html.TextBoxFor(m=>m.Email)
@LabelFor(m=>m.Password)
@Html.PasswordFor(m=>m.Password)
@LabelFor(m=>m.ConfirmPassword)
@Html.PasswordFor(m=>m.ConfirmPassword)
}
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
}
有什么我不应该做的,或者我可以在这里选择另一个更简单的选项吗?如果没有查看代码,很难说,但我的第一个嫌疑犯是js,请确保您已经设置了jQuery验证插件,它应该使用
.blur()
事件触发验证,使用firebug(或类似)检查页面当字段失去焦点时,寻找一个点击DoesUserEmailExist
的ajax帖子,如果没有发生这种情况,那么客户端中缺少了Remote
属性,服务DoesUserEmailExist
看起来正常
旁注:确保数据库中的电子邮件字段具有
唯一的
约束,这是确保没有重复电子邮件的唯一真正方法,即使是使用DoeSuseremaileExist
验证,因为存在并发性。对于初学者,我要感谢你一直以来对我的帮助。如果您首先使用数据库
,我在上面的问题中显示的应该仍然有效,因为它要求您在数据库中设置电子邮件列唯一
,但是要使其首先使用EF code
,我必须对注册操作执行以下操作,还请注意,使用此解决方案,模型中不需要远程注释
:
注册操作
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try //CreateUserAndAccount
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public JsonResult DoesUserEmailExist(string email)
{
var user = Membership.GetUserNameByEmail(email);
return Json(user == null);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
try
{
// Check if email already exists
if (email == null)
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
注意:请注意,此操作将在用户名之前验证电子邮件,并要求您在创建对象之前至少访问数据库一次。我添加了一个注册视图。至于唯一约束,我不确定代码优先实体框架是否可能。考虑到这一点,这已经分配给UserIdYou是对的EF5不支持UNIQUE with code first argh,这可能是我不使用它的原因之一,我更喜欢db first。。。至于这个问题,这个bundle
~/bundles/jqueryval
呈现了所需的js,所以这不是问题,你有没有尝试firebug检查请求?我刚刚运行了它,状态:302找到了
这就是我得到的,这里肯定出了一些问题,请快速通知,我刚刚意识到,在Post下,只有电子邮件字符串的第一个字母被分配给电子邮件。应该是这样吗Email=k
302发现,您的路由有问题,远程属性中的操作和控制器名称正确吗?如果在DoesUserMailExist
中放置断点,它会被命中吗?