예제 #1
0
        public IActionResult Reply(int topicId, ReplyCreationModel replyCreationModel)
        {
            var currentUser = HttpContext.DiscussionUser();

            if (!_siteSettings.CanAddNewReplies())
            {
                _logger.LogWarning("添加回复失败:{@ReplyAttempt}",
                                   new { currentUser.UserName, Result = new FeatureDisabledException().Message });
                return(BadRequest());
            }

            if (_siteSettings.RequireUserPhoneNumberVerified && !currentUser.PhoneNumberId.HasValue)
            {
                _logger.LogWarning("添加回复失败:{@ReplyAttempt}",
                                   new { currentUser.UserName, Result = new UserVerificationRequiredException().Message });
                return(BadRequest());
            }

            var topic = _topicRepo.Get(topicId);

            if (topic == null)
            {
                var errorMessage = "话题不存在";
                _logger.LogWarning("添加回复失败:{@ReplyAttempt}", new { currentUser.UserName, Result = errorMessage });
                ModelState.AddModelError("TopicId", errorMessage);
            }

            if (!ModelState.IsValid)
            {
                _logger.LogModelState("添加回复", ModelState, currentUser.Id, currentUser.UserName);
                return(BadRequest(ModelState));
            }

            var reply = new Reply
            {
                TopicId   = topicId,
                CreatedBy = currentUser.Id,
                Content   = replyCreationModel.Content
            };

            _replyRepo.Save(reply);

            // ReSharper disable once PossibleNullReferenceException
            topic.LastRepliedAt     = _clock.Now.UtcDateTime;
            topic.LastRepliedByUser = currentUser;
            topic.ReplyCount       += 1;
            _topicRepo.Update(topic);

            _logger.LogInformation("添加回复成功:{@ReplyAttempt}",
                                   new
            {
                TopicId = topic.Id, topic.ReplyCount, ReplyId = reply.Id, UserId = currentUser.Id,
                currentUser.UserName
            });
            return(NoContent());
        }