public async Task <IActionResult> CreateCustomer([FromBody] CustomerCreationDto customer) { var customerEntity = _mapper.Map <Customer>(customer); AuthExtensions.CreatePasswordHash(customer.password, out byte[] passwordHash, out byte[] passwordSalt); customer.passwordHash = passwordHash; customer.passwordSalt = passwordSalt; _repository.Customer.CreateCustomer(customerEntity); await _repository.SaveAsync(); var createdCustomer = _mapper.Map <CustomerDto>(customerEntity); return(CreatedAtRoute("CustomerById", new { id = createdCustomer.customerId }, createdCustomer)); }
//[FromForm] is compulsory for getting files with json data public async Task <IActionResult> CreateCustomer([FromForm] CustomerCreationDto customer) { try { //check if profile picture is present var profilePicture = customer.ProfilePicture; if (profilePicture.Length <= 0) { return(BadRequest(new { errorMessage = "Profile picture must be uploaded" })); } //check if customer already exists var existingCustomer = await _repoWrapper.Customer.GetCustomerByEmailAsync(customer.Email); if (existingCustomer != null) { return(BadRequest(new { errorMessage = "Customer already exists" })); } //check if customer object is null if (customer == null) { return(BadRequest(new { errorMessage = "Customer object can not be null" })); } if (!ModelState.IsValid) { return(BadRequest(new { errorMessage = "Invalid customer model" })); } //give the file a unique id Guid uniqueFileId = Guid.NewGuid(); //give file a unique name to prevent overwriting var uniqueFileName = uniqueFileId + profilePicture.FileName.Replace(" ", "_");//replace spaces with underscore //specify folder to save uploaded files var filePath = Path.Combine("Uploads/Images", uniqueFileName); //this works, but saves file inside server, not a specific folder // using(var fileStream = new FileStream(profilePicture.FileName, FileMode.Create)) //save profile picture using (var fileStream = new FileStream(filePath, FileMode.Create)) { await profilePicture.CopyToAsync(fileStream); } //map incoming customer object of CustomerCreationDto to the Customer model class var customerEntity = _mapper.Map <Customer>(customer); //add the unique filename to customerentity object and save to db customerEntity.ProfilePicture = uniqueFileName; _repoWrapper.Customer.CreateCustomer(customerEntity); await _repoWrapper.SaveAsync(); //map the created customer to the CustomerCreationDto // var createdCustomer = _mapper.Map<CustomerCreationDto>(customerEntity); --causes error //return created customer //return Created($"/api/customers/{createdCustomer.CustomerId}", createdCustomer); return(Created($"/api/customers/{customerEntity.CustomerId}", customerEntity)); } catch (Exception) { //if an exception occurs return(this.StatusCode(501)); } }