コード例 #1
0
        public async Task <IActionResult> Delete(int userId, int id)
        {
            // Are you who you say you are?
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            // Check if it is actually the id of a photo that belongs to the user and make sure
            // that they have at least 2 photos
            var user = await _repo.GetUser(userId);

            if (!user.Photos.Any(p => p.Id == id))
            {
                return(Unauthorized());
            }

            if (user.Photos.Count < 2)
            {
                return(BadRequest("You need at least one photo in your album"));
            }

            // Check if we are deleting the one that is set to main
            var photoFromRepo = await _repo.GetPhoto(id);

            var DeletingMainPhoto = photoFromRepo.IsMain;

            _repo.Delete(photoFromRepo);

            if (DeletingMainPhoto)
            {
                // Make the first one you find as the main photo
                var anyPhoto = await _repo.GetFirstPhoto(userId);

                anyPhoto.IsMain = true;
            }

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            return(BadRequest("Could not delete the photo"));
        }