public IActionResult Put(int id, [FromForm] NotebookViewModel notebookViewModel) { if (ModelState.IsValid) { var currentUser = User.Claims.Single(c => c.Type == ClaimTypes.Email).Value; if (!_notebookService.CanUserEdit(id, currentUser)) { return(Forbid()); } var notebook = _context.Notebook.SingleOrDefault(b => b.Id == id); if (notebook == null) { return(NotFound()); } else { if (notebookViewModel.ImageFile != null) { if (notebook.Image != null) { // Delete the old image file var oldFilePath = _hostingEnvironment.WebRootPath + notebook.Image; System.IO.File.Delete(oldFilePath); } var fileName = Guid.NewGuid() + notebookViewModel.ImageFile.FileName; var imageFilesFolderPath = Path.Combine(_hostingEnvironment.WebRootPath, "Images"); var filePath = Path.Combine(imageFilesFolderPath, fileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { notebookViewModel.ImageFile.CopyTo(fileStream); } notebook.Image = Path.Combine("/Images/", fileName); notebook.ImageName = notebookViewModel.ImageFile.FileName; } notebook.Name = notebookViewModel.Name; notebook.Public = notebookViewModel.Public; _context.SaveChanges(); return(Ok(notebook)); } } else { return(BadRequest(ModelState)); } }
public IActionResult Post([FromBody] NotebookPageViewModel notebookPageViewModel) { var currentUser = User.Claims.Single(c => c.Type == ClaimTypes.Email).Value; if (!_notebookService.CanUserEdit(notebookPageViewModel.NotebookId, currentUser)) { return(Forbid()); } if (ModelState.IsValid) { int newPageNumber = 1; if (_context.NotebookPage.Any()) { newPageNumber = _context.NotebookPage.Max(np => np.PageNumber) + 1; } _context.NotebookPage.Add(new NotebookPage { NotebookId = notebookPageViewModel.NotebookId, PageNumber = newPageNumber, Title = notebookPageViewModel.Title, Content = notebookPageViewModel.Content }); _context.SaveChanges(); var notebookPage = _context.NotebookPage.Single(np => np.NotebookId == notebookPageViewModel.NotebookId && np.PageNumber == newPageNumber); return(Ok(notebookPage)); } else { return(BadRequest(ModelState)); } }