ASP.NET Core - CRUD cho User module

Sau đây, NET Core VN xin giới thiệu CRUD thông tin User trong ASP.NET Core.

1. Lấy thông tin User

[HttpGet]
        public async Task<IActionResult> GetUsers()
        {
            var users = await _userManager.Users.ToListAsync();

            var userDtos = new List<UserDto>();
            foreach (var user in users)
            {
                var userDto = _mapper.Map<UserDto>(user);

                //set isLocked
                userDto.IsLocked = await _userManager.IsLockedOutAsync(user);

                var roleNames = _userManager.GetRolesAsync(user).Result;
                userDto.Role = new List<RoleDto>();
                foreach (var roleName in roleNames)
                {
                    var role = _roleManager.FindByNameAsync(roleName).Result;
                    var roleDto = _mapper.Map<RoleDto>(role);
                    userDto.Role.Add(roleDto);
                }
                userDtos.Add(userDto);
            }
            return Ok(userDtos);
        }
 

2. Thêm thông tin User

[HttpPost]
        public async Task<IActionResult> PostUser([FromBody] UserDto userDto)
        {
            var jsonResult = new JsonResult("");

            if (userDto == null)
            {
                _logger.LogError(nameof(PostUser), userDto);
                return BadRequest();
            }

            var user = new User();
            user.Name = userDto.Name;
            user.NickName = userDto.NickName;
            user.Teaser = userDto.Teaser;
            user.Email = userDto.Email;
            user.PhoneNumber = userDto.PhoneNumber;
            user.Birthday = userDto.Birthday;
            user.UserName = userDto.Email;
            user.UserPassword = userDto.UserPassword;

            var result = await _userManager.CreateAsync(user, user.UserPassword);

            if (!result.Succeeded)
            {
                jsonResult.StatusCode = 0;
                foreach (var error in result.Errors)
                {
                    jsonResult.ContentType += error.Description;
                }
                _logger.LogError(nameof(PostUser), result.Errors.ToString());
                if (!Helper.IsLocalRequest(HttpContext))
                {
                    Helper.SendMail("nguyenminhtuanitc@gmail.com", "nguyenminhtuanitc@gmail.com", "From " + HttpContext.Request.Host + ": " + nameof(PostUser), jsonResult.ContentType);
                }
                return Ok(jsonResult);
            }
            jsonResult.StatusCode = 1;
            jsonResult.ContentType = "Added User Successfully!";

            return Ok(jsonResult);
        }

3. Sửa thông tin User

[HttpPut]
        [Route("{id}")]
        public async Task<IActionResult> PutUser(string id, [FromBody] UserDto userDto)
        {
            var jsonResult = new JsonResult("");

            if (id == null)
            {
                _logger.LogError(nameof(PutUser), userDto);
                return BadRequest();
            }

            var user = await _userManager.FindByIdAsync(id.ToString());

            if (user == null)
            {
                _logger.LogError(nameof(PutUser), userDto);
                return NotFound();
            }

            user.Name = userDto.Name;
            user.NickName = userDto.NickName;
            user.Teaser = userDto.Teaser;
            user.Email = userDto.Email;
            user.PhoneNumber = userDto.PhoneNumber;
            user.Birthday = userDto.Birthday;
            user.UserName = userDto.UserName;

            var result = await _userManager.UpdateAsync(user);

            if (!result.Succeeded)
            {
                jsonResult.StatusCode = 0;
                foreach (var error in result.Errors)
                {
                    jsonResult.ContentType += error.Description;
                }
                _logger.LogError(nameof(PutUser), result.Errors.ToString());
                if (!Helper.IsLocalRequest(HttpContext))
                {
                    Helper.SendMail("nguyenminhtuanitc@gmail.com", "nguyenminhtuanitc@gmail.com", "From " + HttpContext.Request.Host + ": " + nameof(PutUser), jsonResult.ContentType);
                }
                return Ok(jsonResult);
            }
            jsonResult.StatusCode = 1;
            jsonResult.ContentType = "Edited User Successfully!";

            return Ok(jsonResult);
        }

4. Xóa thông tin User

[HttpDelete]
        [Route("{id}")]
        public async Task<IActionResult> DeleteUser(string id)
        {
            if (id == null)
            {
                _logger.LogError(nameof(DeleteUser), id);
                return BadRequest();
            }

            var _user = await _userManager.FindByIdAsync(id.ToString());

            var result = await _userManager.DeleteAsync(_user);

            return CreatedAtAction("GetUsers", new { id = _user.Id }, _user);
        }

Bài viết liên quan

+61404577839