Example #1
0
        public async Task <IActionResult> UpdatePost(int id, [FromBody] PostUpdateResource postUpdate)
        {
            if (postUpdate == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(new MyUnprocessableEntityObjectResult(ModelState));
            }

            var post = await _postRepository.GetPostByIdAsync(id);

            if (post == null)
            {
                return(NotFound());
            }

            post.LastModified = DateTime.Now;
            _mapper.Map(postUpdate, post);

            if (!await _unitOfWork.SaveAsync())
            {
                throw new Exception($"Updating post {id} failed when saving.");
            }
            return(NoContent());
        }
Example #2
0
        public async Task <IActionResult> UpdatePost(int id, [FromBody] PostUpdateResource postUpdateResource)
        {
            if (postUpdateResource == null)
            {
                return(BadRequest());//400错误
            }
            var resultValidator = _validator.Validate(postUpdateResource);

            if (!resultValidator.IsValid)
            {
                string errorMessage = string.Join(",", resultValidator.Errors);
                return(UnprocessableEntity(errorMessage));//返回422状态码
            }

            var post = await _postRepository.GetPostByIdAsync(id);

            if (post == null)
            {
                return(NotFound());
            }

            _mapper.Map(postUpdateResource, post);

            if (!await _unitOfWork.SaveAsync())
            {
                throw new Exception($"updating post {id} fields when saving  ");
            }

            return(NoContent());
        }