【问题标题】:Register using username instead of Email in ASP.NET MVC 5?在 ASP.NET MVC 5 中使用用户名而不是电子邮件注册?
【发布时间】:2024-01-19 07:21:01
【问题描述】:

我已将RegisterViewModel 更改为使用Username 而不是Email,并在Register POST 方法中初始化new ApplicationUser 时省略了电子邮件部分:

       public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Username/*, Email = model.Username*/ };
...

但是当我通过用户名注册时出现错误:

电子邮件不能为空或为空。

我该如何解决这个问题,有没有办法不允许使用相同的用户名?

【问题讨论】:

标签: asp.net-mvc asp.net-identity


【解决方案1】:

您可以将 RegisterViewModel 更改为

public class RegisterViewModel 
{
    [Remote("IsUserNameExist", "User", "", ErrorMessage = "this username exist", HttpMethod = "POST")]
    public string UserName { set; get; }
    //todo: other fileds......

}

并在您的 UserController 中编写您现有的验证操作结果

    [HttpPost]
    [AllowAnonymous]
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true,  Duration = 0, VaryByParam = "*")]
    public virtual JsonResult IsUserNameExist(string userName)
    {
        var check = _userService.CheckUserNameExist(userName);
        return check ? Json(false) : Json(true);
    }

【讨论】:

    最近更新 更多