public async Task <IActionResult> PutRequest([FromRoute] string id, [FromBody] Request request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != request.RequestId) { return(BadRequest()); } if (!UsertExists(request.Username)) { return(BadRequest("User does not exist.")); } if (!RequestTypeExists(request.RequestTypeId)) { return(BadRequest("Request Type does not exist.")); } if (!RequestStates.IsValidState(request.State)) { return(BadRequest("Request State does not exist.")); } _context.Entry(request).State = EntityState.Modified; try { if (request.Attachment != null) { try { string folderName = "forms"; if (string.IsNullOrWhiteSpace(_hostingEnvironment.WebRootPath)) { _hostingEnvironment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"); } string webRootPath = _hostingEnvironment.WebRootPath; string newPath = Path.Combine(webRootPath, folderName); string attachmentDir = Path.Combine(newPath, request.RequestId); if (!Directory.Exists(attachmentDir)) { Directory.CreateDirectory(attachmentDir); } string fileName = ContentDispositionHeaderValue.Parse(request.Attachment.ContentDisposition).FileName.Trim('"'); string fullPath = Path.Combine(attachmentDir, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { request.Attachment.CopyTo(stream); } request.AttachmentPath = string.Format("{0}://{1}/{2}/{3}/{4}", Request.Scheme, Request.Host.Value, folderName, request.RequestId, fileName); } catch (Exception e) { Console.WriteLine(e.Message); return(BadRequest(e)); //throw e; } } await _context.SaveChangesAsync(); if (request.State != RequestStates.DB_REQUESTED) { var smtpClient = new SmtpClient { Host = "smtp.gmail.com", // set your SMTP server name here Port = 587, // Port EnableSsl = true, Credentials = new NetworkCredential("*****@*****.**", "noy3k.mail_svc") }; using (var message = new MailMessage("*****@*****.**", _context.Users.Find(request.Username).Email) { Subject = string.Format("Status of the Request {0} has changed to {1}", request.RequestId, request.State), Body = string.Format("Status of the Request {0} has changed to {1}", request.RequestId, request.State) }) { smtpClient.Send(message); } } } catch (DbUpdateConcurrencyException) { if (!RequestExists(id)) { return(NotFound()); } else { throw; } } catch (Exception e) { return(this.BadRequest(e.Message)); } return(NoContent()); }