public async Task <AddNewsViewModel> Handle(AddNewsCommand request, CancellationToken cancellationToken) { var userId = HttpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier); BaseUser user = _context.BaseUsers.FirstOrDefault(u => u.Id == userId); if (user == null) { throw new CustomException(new Error { ErrorType = ErrorType.Unauthorized, Message = Localizer["Unauthorized"] }); } var fileEntity = await _context.Files.FirstOrDefaultAsync(f => f.Id == request.FileId, cancellationToken); if (fileEntity == null) { throw new CustomException(new Error { ErrorType = ErrorType.FileNotFound, Message = Localizer["FileNotFound"] }); } Domain.Models.News news = new Domain.Models.News { Description = request.Description, Title = request.Title, FileId = request.FileId }; await _context.News.AddAsync(news, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return(new AddNewsViewModel { News = _mapper.Map <NewsDto>(news) }); }
public ActionResult Add(NewsViewModel model) { if (!ModelState.IsValid) { return View(model); } int cityId = (int)Session["City"]; News news = new News { Title = model.Title, Text = model.Text, Time = DateTime.Now, CityId = cityId }; try { newsRepository.Insert(news); TempData["Success"] = "Новость добавлена"; } catch(Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex); ModelState.AddModelError("", "Ошибка при добавлении записи. Повторите попытку позже"); return View(model); } return View(new NewsViewModel()); }
public async Task <Unit> Handle(RemoveNewsCommand request, CancellationToken cancellationToken) { var userId = HttpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier); BaseUser user = _context.BaseUsers.FirstOrDefault(u => u.Id == userId); if (user == null) { throw new CustomException(new Error { ErrorType = ErrorType.Unauthorized, Message = Localizer["Unauthorized"] }); } Domain.Models.News news = await _context.News. FirstOrDefaultAsync(n => n.NewsId == request.NewsId, cancellationToken); if (news != null) { _context.News.Remove(news); await _context.SaveChangesAsync(cancellationToken); } return(Unit.Value); }