Register with username using identity 2.1

前端 未结 1 1680
轻奢々
轻奢々 2021-01-26 13:21

New .net identity system uses email and password as registration pair. I would like to change it as it was before and use username for loging users to my webapp. Also I\'d like

1条回答
  •  情书的邮戳
    2021-01-26 13:48

    Actually the old identity framework system (v 1.0) registration UI different to the new version. You can easily understand what exactly happening in the registration code.

    New out of the box registration code is:

            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task Register(RegisterViewModel model)
            {
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
    
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
    
                        return RedirectToAction("Index", "Home");
                    }
                    AddErrors(result);
                }
    
                // If we got this far, something failed, redisplay form
                return View(model);
            }
    

    You can see that the Username and Email both uses model.Email.

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
    

    Update your code as below

    Register method

    [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
    
                UserManager.UserValidator = new UserValidator(UserManager)
                {
                    RequireUniqueEmail = false,
                };
    
                var user = new ApplicationUser { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
    
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
    
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
    
            // If we got this far, something failed, redisplay form
            return View(model);
        }
    

    RegisterViewModel

    public class RegisterViewModel
        {
            [Required]
            [Display(Name = "UserName")]
            public string UserName { 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")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }
        }
    

    LoginViewModel

    public class LoginViewModel
        {
            [Required]
            [Display(Name = "UserName")]
            public string UserName { get; set; }
    
            [Required]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }
    
            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }
    

    Further you need to update other view models not to use email and instead use

    [Required]
        [Display(Name = "UserName")]
        public string UserName { get; set; }
    

    Then update all views to use UserName instead Email like below.

    @model WebApplication2.Models.RegisterViewModel
    @{
        ViewBag.Title = "Register";
    }
    
    

    @ViewBag.Title.

    @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken()

    Create a new account.


    @Html.ValidationSummary("", new { @class = "text-danger" })
    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
    @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
    @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
    } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

    Hope this helps.

    0 讨论(0)
提交回复
热议问题