public async Task <IActionResult> UploadImage(int catalogItemId) { using (var db = new CatalogDb()) { var item = db.CatalogItems.SingleOrDefault(i => i.Id == catalogItemId); if (item == null) { return(NotFound(new { Message = $"Item with id {catalogItemId} not found." })); } string rootPath = _hostingEnvironment.WebRootPath ?? "wwwroot"; string imagePath = Path.Combine(rootPath, "Images"); // Create if no exists Directory.CreateDirectory(imagePath); string extension = GetExtensionFromContentType(Request.ContentType); string fileName = Path.Combine(imagePath, $"{catalogItemId}{extension}"); using (var stream = new FileStream(fileName, FileMode.Create)) { await Request.Body.CopyToAsync(stream); } item.PictureFileName = Path.GetFileName(fileName); item.PictureUri = $"{ImageBaseUri}/{item.PictureFileName}"; db.SaveChanges(); } return(Ok()); }
public IActionResult DeleteProduct(int id) { using (var db = new CatalogDb()) { var product = db.CatalogItems.SingleOrDefault(x => x.Id == id); if (product == null) { return(NotFound()); } db.CatalogItems.Remove(product); db.SaveChanges(); return(NoContent()); } }
public IActionResult UpdateProduct([FromBody] CatalogItem productToUpdate) { using (var db = new CatalogDb()) { var item = db.CatalogItems.SingleOrDefault(i => i.Id == productToUpdate.Id); if (item == null) { return(NotFound(new { Message = $"Item with id {productToUpdate.Id} not found." })); } db.CatalogItems.Remove(item); ChangeUriPlaceholder(productToUpdate); db.CatalogItems.Add(productToUpdate); db.SaveChanges(); return(CreatedAtAction(nameof(GetItemById), new { id = productToUpdate.Id }, null)); } }
public IActionResult CreateProduct([FromBody] CatalogItem product) { using (var db = new CatalogDb()) { var item = new CatalogItem { CatalogBrandId = product.CatalogBrandId, CatalogTypeId = product.CatalogTypeId, Description = product.Description, Name = product.Name, PictureFileName = product.PictureFileName, Price = product.Price }; item.Id = db.CatalogItems.Max(r => r.Id) + 1; ChangeUriPlaceholder(item); db.CatalogItems.Add(item); db.SaveChanges(); return(CreatedAtAction(nameof(GetItemById), new { id = item.Id }, item)); } }