コード例 #1
0
        public async Task <string> Add(AccViewModel model)
        {
            try
            {
                string errorMessage = null;
                var    user         = new IdentityUserV2
                {
                    Email    = model.RegisterEmail,
                    UserName = model.RegisterName,
                    NickName = model.UserV2.NickName,
                    City     = model.UserV2.City,
                    Position = model.UserV2.Position
                };
                string[] deptInfo = model.Department.Split(',');
                user.Department = deptInfo[1];
                user.DeptCode   = deptInfo[0].Trim(',');
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    logger.LogWarning("添加用户{LogType}{CustomProperty}", "Operate", user.UserName);
                    if (user.DeptCode != "0")
                    {
                        int deptId = deptManager.GetDeptId(user.DeptCode);
                        var ids    = await deptManager.GetRolesIdAsync(deptId);

                        foreach (var id in ids)
                        {
                            context.UserRoles.Add(new IdentityUserRole <string> {
                                UserId = user.Id, RoleId = id
                            });
                        }
                        context.SaveChanges();
                    }
                    return(errorMessage);
                }
                foreach (var error in result.Errors)
                {
                    errorMessage += error.Description + "\r\n";
                }
                logger.LogWarning("添加用户失败{LogType}{CustomProperty}", "Operate", errorMessage);
                return(errorMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }