public async Task <IActionResult> AddPhotoForCarmodel(int carmodelId, [FromForm] PhotoForCreationDto photoForCreationDto) { // 原先課程的範例是 上傳 user 的圖片, 所以需要確認 ID, 這邊不用 // check the user was attempting to update their profile matches the token // if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) // { // return Unauthorized(); // } var carModelFromRepo = await _repo.GetCarModel(carmodelId); var file = photoForCreationDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDto); // if carmodel doesn't have main photo if (!carModelFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } carModelFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { // return Ok(); // do not return "photo" object directly, use object of PhotoForReturnDto // photo will have Id after SaveAll() success var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { carmodelId = carmodelId, id = photo.Id }, photoToReturn)); } else { return(BadRequest("Could not add the photo")); } }
public async Task <IActionResult> GetCarModel(int id) { var carModel = await _repo.GetCarModel(id); // return object of Dto class instead of Model class var carModelToReturn = _mapper.Map <CarModelForDetailedDto>(carModel); return(Ok(carModelToReturn)); }
public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto) { var sender = await _repo.GetUser(userId); if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } messageForCreationDto.SenderId = userId; var recipient = await _repo.GetCarModel(messageForCreationDto.RecipientId); if (recipient == null) { return(BadRequest("Could not find user")); } var message = _mapper.Map <Message>(messageForCreationDto); _repo.Add(message); if (await _repo.SaveAll()) { var messageToReturn = _mapper.Map <MessageToReturnDto>(message); // return CreatedAtRoute("GetMessage", new {userId, id = message.Id }, messageToReturn); return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn)); } throw new System.Exception("Creating the message failed on save"); }