> 文章列表 > 第59章 用户增、修、删的后端实现

第59章 用户增、修、删的后端实现

第59章 用户增、修、删的后端实现

1 WebApi.Controllers.CustomerController. CreateCustomer

 /// <param name="customerModel">用户模型的1个指定实例</param>

        /// <summary>

        /// 【添加用户--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     通过用户模型的1个指定实例,把1个用户实体1个指定实例持久化到用户表中。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     用户实体的1个指定实例。

        /// </returns>

        [HttpPost]

        [Authorize(PermissionsPolicy.Name)]

        public async Task<MessageModel<Customer>> CreateCustomer([FromBody] CustomerModel customerModel)

        {

            if (customerModel != null)

            {

                Customer _customer = AutoMapperConfiguration.Mapper.Map<Customer>(customerModel);

                foreach (var item in customerModel.RoleIdList)

                {

                    Role _role = await _customerService.GetRoleByIdAsync(item);

                    if (_role.Name.Equals("Administrator"))

                    {

                        _customer.IsSystemAccount = true;

                        break;

                    }

                }

                _customer.CreatedDateTime = DateTime.Now;

                _customer.UpdatedDateTime = DateTime.Now;

                await _customerService.InsertCustomerAsync(_customer);

                CustomerPassword _customerPassword = new CustomerPassword

                {

                    CustomerId = _customer.Id,

                    PasswordFormat = PasswordFormat.Hashed,

                };

                var saltKey = _encryptionService.CreateSaltKey(CustomerPassword.PasswordSaltKeySize);

                _customerPassword.PasswordSalt = saltKey;

                _customerPassword.Password = _encryptionService.CreatePasswordHash("111111", saltKey, CustomerPassword.DefaultHashedPasswordFormat);

                await _customerService.InsertCustomerPasswordAsync(_customerPassword);

                IList<CustomerRole> _customerRoleList = new List<CustomerRole>();

                foreach (var item in customerModel.RoleIdList)

                {

                    CustomerRole _customerRole = new CustomerRole();

                    _customerRole.CustomerId = _customer.Id;

                    _customerRole.RoleId = item;

                    _customerRoleList.Add(_customerRole);

                }

                await _customerService.AddCustomerRoleAsync(_customerRoleList);

               

               return MessageModel<Customer>.GetSuccess("成功添加指定用户。", _customer);

            }

            return MessageModel<Customer>.Fail("添加指定用户失败!", 500);

        }

2 WebApi.Controllers.CustomerController. EditCustomer

/// <param name="customerModel">用户模型的1个指定实例。</param>

        /// <summary>

        /// 【更新用户--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     通过用户模型的1个指定实例,对1个用户实体1个指定实例进行修改操作并持久化到用户表的指定行中。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     用户实体的1个指定实例。

        /// </returns>

        [HttpPut]

        [Authorize(PermissionsPolicy.Name)]

        public async Task<MessageModel<Customer>> EditCustomer([FromBody] CustomerModel customerModel)

        {

            Customer _customer = await _customerService.GetCustomerByIdAsync(customerModel.Id);

            /* if (_customer != null && customerModel != null)

             {

                 _customer.Name = customerModel.Name;

                 _customer.Email = customerModel.Email;

                 _customer.Phone = customerModel.Phone;

                 _customer.IsSystemAccount = customerModel.IsSystemAccount;

                 _customer.IsActive = customerModel.IsActive;

                 _customer.Deleted = customerModel.Deleted;

                 _customer.UpdatedDateTime = DateTime.Now;

                await _customerService.UpdateCustomerAsync(_customer);

                return MessageModel<Customer>.GetSuccess("成功更新指定用户。", _customer);

             }*/

            if (_customer != null && customerModel != null)

            {

                /*

               注意:

                 “AutoMapperConfiguration.Mapper.Map(customerModel, _customer)”方法中必须包含“_customer”参数实例,否则在赋值映射时会导致

                   _customer.CreatedDateTime属性实例为:0001-01-01 00:00:00.0000000

                  _customer.Avatar属性实例为:空字符串。

                  1、如果不包含“_customer”参数实例其赋值映射过程的实质为:new Customer()=customerModel; _customer=new Customer();所以才会导致上述状况的产生。

                  2、如果包含“_customer”参数实例其赋值映射过程的实质为: _customer=customerModel;从而避免了上述状况的产生。

              */

                _customer = AutoMapperConfiguration.Mapper.Map(customerModel, _customer);

                IList<Role> _currentRoleList = await _customerService.GetRoleByCustomerIdAsync(customerModel.Id);

                IList<Role> _roleList = await _customerService.GetAllRolesAsync();

                IList<Role> _allRoleList = _roleList.Where(role => role.IsActive.Equals(true)).ToList();

                foreach (var item in _allRoleList)

                {

                    if (customerModel.RoleIdList.Contains(item.Id))

                    {

                        if (_currentRoleList.All(role => role.Id != item.Id))

                        {

                            await _customerService.AddCustomerRoleAsync(new CustomerRole { CustomerId = _customer.Id, RoleId = item.Id });

                            if (item.Name.Equals("Administrator"))

                                _customer.IsSystemAccount = true;

                            _currentRoleList.Add(item);

                        }

                    }

                    else

                    {

                        if (_currentRoleList.Any(roleId => roleId.Id == item.Id))

                        {

                            await _customerService.RemoveCustomerRoleMappingAsync(_customer, item);

                            if (item.Name.Equals("Administrator"))

                                _customer.IsSystemAccount = false;

                            int index = _currentRoleList.ToList().FindIndex(role => role.Id.Equals(item.Id));

                            _currentRoleList.RemoveAt(index);

                        }

                    }

                }

                _customer.RoleCollection = _currentRoleList;

                _customer.UpdatedDateTime = DateTime.Now;

                await _customerService.UpdateCustomerAsync(_customer);

                return MessageModel<Customer>.GetSuccess("成功更新指定用户。", _customer);

            }

            return MessageModel<Customer>.Fail("更新指定用户失败!", 500);

        }

3 WebApi.Controllers.CustomerController. ResertPassword

/// <param name="customerId">1个指定的长整型值。</param>

        /// <summary>

        /// 【密码重置--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     1个指定用户的密码进行重置操作

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     消息模型纪录的1个指定实例,该实例存储当前“Api”方法的执行操作结果,为客户端页面的渲染提供数据支撑。

        /// </returns>

        [Authorize(PermissionsPolicy.Name)]

        [HttpGet]

        public async Task<MessageModel<bool>> ResertPassword(long customerId)

        {

            CustomerPassword _customerPassword = await _customerService.GetCustomerPasswordsAsync(customerId);

            if (_customerPassword != null)

            {

                var saltKey = _encryptionService.CreateSaltKey(CustomerPassword.PasswordSaltKeySize);

                _customerPassword.PasswordSalt = saltKey;

                _customerPassword.Password = _encryptionService.CreatePasswordHash("1", saltKey, CustomerPassword.DefaultHashedPasswordFormat);

                await _customerService.UpdateCustomerPasswordAsync(_customerPassword);

                return MessageModel<bool>.GetSuccess($"密码重置成功!", true);

            }

            return MessageModel<bool>.GetSuccess("密码重置失败!", true);

        }

4 WebApi.Controllers.CustomerController. Delete

         /// <param name="customerId">1个指定的长整型值。</param>

        /// <summary>

        /// 【删除1个用户--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     从用户表中删除1行指定的数据

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     消息模型纪录的1个指定实例,该实例存储当前“Api”方法的执行操作结果,为客户端页面的渲染提供数据支撑。

        /// </returns>

        [Authorize(PermissionsPolicy.Name)]

        [HttpDelete]

        public async Task<MessageModel<Customer>> Delete(long customerId)

        {

            Customer _customer = await _customerService.GetCustomerByIdAsync(customerId);

            if (_customer != null)

            {

                await _customerService.DeleteCustomerAsync(_customer);

                //如果1个指定的用户实例是被逻辑删除就不要定义用户头像、用户密码和用户角色映射的逻辑删除和物理删除操作。

                if (!string.IsNullOrEmpty(_customer.Avatar) && !_nopFileProvider.GetFileName(_customer.Avatar).Equals("Default.jpg"))

                {

                    //去除网络格式路径字符中的第一个字符“~/”

                    _customer.Avatar = _customer.Avatar.Replace("~/", string.Empty).TrimStart('/');

                    //去除网络格式路径字符中的最后一个字符“/”

                    var pathEnd = _customer.Avatar.EndsWith('/') ? Path.DirectorySeparatorChar.ToString() : string.Empty;

                    //通过拼接操作,拼接出与之相对应的1个本地格式的路径字符串。

                    string _avatarPath = _nopFileProvider.Combine(_nopFileProvider.WebRootPath ?? string.Empty, _customer.Avatar) + pathEnd;

                    _nopFileProvider.DeleteFile(_avatarPath);

                }

                CustomerPassword _customerPassword = await _customerService.GetCustomerPasswordsAsync(customerId);

                if (_customerPassword != null)

                    await _customerService.DeleteCustomerPasswordAsync(_customerPassword);

                IList<Role> _currentRoleList = await _customerService.GetRoleByCustomerIdAsync(customerId);

                foreach (var item in _currentRoleList)

                {

                    await _customerService.RemoveCustomerRoleMappingAsync(_customer, item);

                }

               return MessageModel<Customer>.GetSuccess("成功删除单个用户!", _customer);

            }

            return MessageModel<Customer>.Fail("单个用户删除失败!", 500);

        }

5 WebApi.Controllers.CustomerController. DeleteSelected

         /// <param name="selectIdArray">用户实体多个指定实例的长整型编号值的字符串集,值之间用进行分割。</param>

        /// <summary>

        /// 【删除多个所选用户--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     从用户表中删除1行指定的数据。

        /// 说明:

        ///     如果后端使用List<int/> /ICollection<int/> 参数实例,进行批量删除操作,则后端都必须使用“[HttpPost]”所标记的方法,未测试?

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     消息模型纪录的1个指定实例,该实例存储当前“Api”方法的执行操作结果,为客户端页面的渲染提供数据支撑。

        /// </returns>

        [Authorize(PermissionsPolicy.Name)]

        [HttpDelete]

        public async Task<MessageModel<bool>> DeleteSelected(string selectIdArray)

        {

            string[] _idArray = selectIdArray.Split(",").ToArray();

            List<Customer> _customerList = new List<Customer>();

            foreach (string id in _idArray)

            {

                long _id = Convert.ToInt64(id);

                Customer _model = await _customerService.GetCustomerByIdAsync(_id);

                if (_model != null && !_model.Email.Equals("admin@yourStore.com"))

                    _customerList.Add(_model);

            }

            if(_customerList.Count>0)

            {

                foreach (Customer _customer in _customerList)

                {

                    await _customerService.DeleteCustomerAsync(_customer);

                    //如果1个指定的用户实例是被逻辑删除就不要定义用户头像、用户密码和用户角色映射的逻辑删除和物理删除操作。

                    if (!string.IsNullOrEmpty(_customer.Avatar) && !_nopFileProvider.GetFileName(_customer.Avatar).Equals("Default.jpg"))

                    {

                        //去除网络格式路径字符中的第一个字符“~/”

                        _customer.Avatar = _customer.Avatar.Replace("~/", string.Empty).TrimStart('/');

                        //去除网络格式路径字符中的最后一个字符“/”

                        var pathEnd = _customer.Avatar.EndsWith('/') ? Path.DirectorySeparatorChar.ToString() : string.Empty;

                        //通过拼接操作,拼接出与之相对应的1个本地格式的路径字符串。

                        string _avatarPath = _nopFileProvider.Combine(_nopFileProvider.WebRootPath ?? string.Empty, _customer.Avatar) + pathEnd;

                        _nopFileProvider.DeleteFile(_avatarPath);

                    }

                    CustomerPassword _customerPassword = await _customerService.GetCustomerPasswordsAsync(_customer.Id);

                    if (_customerPassword != null)

                        await _customerService.DeleteCustomerPasswordAsync(_customerPassword);

                    IList<Role> _currentRoleList = await _customerService.GetRoleByCustomerIdAsync(_customer.Id);

                    if( _currentRoleList != null && _currentRoleList.Count > 0)

                    {

                        foreach (var item in _currentRoleList)

                        {

                            await _customerService.RemoveCustomerRoleMappingAsync(_customer, item);

                        }

                    }

                }

                return MessageModel<bool>.GetSuccess($"成功删除{_customerList.Count}个用户!", true);

            }

            return MessageModel<bool>.Fail("多个用户删除失败!", 500);

        }

对以上功能更为具体实现和注释见:230412_046shopDemo(用户增、修、删的后端实现)。

安陆市图书馆