public async Task <IActionResult> RegisterAsync(RegisterViewModel model, string returnUrl = null) { if (!_advancedSettings.EnableRegister) { return(NotFound()); } returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new Blog.Data.Domains.User { UserName = model.Email, Email = model.Email, DisplayName = model.Email, }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { await SendEmailConfirmationMessageAsync(user); return(RedirectToAction("RegisterConfirmation", new { email = model.Email })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task CreateAsync([FromBody] UserEditModel model) { var entity = _userFactory.ToEntity(model); entity.Id = GuidGenerator.Instance.Create().ToString(); IdentityResult result; if (!string.IsNullOrEmpty(model.Password)) { result = await _userManager.CreateAsync(entity, model.Password); } else { result = await _userManager.CreateAsync(entity); } if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } if (model.RoleIds?.Any() == true) { var roles = new List <Role>(); foreach (var item in model.RoleIds) { var role = await _roleManager.FindByIdAsync(item); if (role != null) { roles.Add(role); } } if (roles.Any()) { await _userManager.AddToRolesAsync(entity, roles.Select(t => t.Name)); } } }