public async Task <ActionResult> Post([FromBody] ProductInputModel model) { if (this.User.IsInRole("Administrator")) { if (_productsService.All().Any(p => p.Name == model.Name)) { return(BadRequest(new BadRequestViewModel { Message = "Product with the given name already exists." })); } var productCategory = _categoriesService.FindByName(model.Category); if (productCategory != null) { var ingredients = new List <IngredientDto>(); foreach (var ingredientName in model.Ingredients) { var ingredient = this._ingredientsService.FindByName(ingredientName); if (ingredient != null) { ingredients.Add(ingredient); } else { return(BadRequest(new BadRequestViewModel { Message = $"{ingredientName} ingredient not found." })); } } var productDto = new ProductDto { Name = model.Name, CategoryId = productCategory.Id, Description = model.Description, Image = model.Image, Weight = model.Weight, Price = model.Price, Ingredients = ingredients.Select(i => new IngredientDto { Id = i.Id, Name = i.Name }).ToList() }; try { await this._productsService.CreateAsync(productDto); var createdProductDto = this._productsService .All() .First(p => p.Name == productDto.Name); var createdProductViewModel = this._mapper.Map <ProductViewModel>(createdProductDto); await this._productsHubContext.Clients.All.BroadcastProduct(createdProductViewModel); return(Ok(new { Message = "Product added successfully." })); } catch (Exception) { return(BadRequest(new BadRequestViewModel { Message = "Something went wrong." })); } } return(BadRequest(new BadRequestViewModel { Message = "Category not found." })); } return(Unauthorized()); }