public IActionResult Post(int customerId, [FromBody] CustomerDto dto) { dto.Id = customerId; var cust = DtoConverter.DtoToCustomer(dto); _dao.Upsert(cust); return(this.Ok()); }
public IActionResult PostWithErrorHandling(int customerId, [FromBody] CustomerDto dto) { dto.Id = customerId; Log("POST with {0}", customerId); // handle validation errors at DTO level if (!this.ModelState.IsValid) { Log("Model State invalid"); return(this.BadRequest(this.ModelState)); } // handle customer creation errors var cust = DtoConverter.DtoToCustomer(dto); if (cust == null) { Log("Customer could not be created from DTO"); return(this.BadRequest("Customer could not be created from DTO")); } // hook into the domain event DomainEvents.EmailAddressChanged += NotifyCustomerWhenEmailChanged; try { _dao.Upsert(cust); return(this.Ok()); } catch (Exception ex) { // handle database errors var errMsg = $"Exception: {ex.Message}"; Log("Exception: {0}", ex.Message); return(new ContentResult { Content = errMsg, StatusCode = 500 }); } finally { // unhook from the domain event no matter what happens DomainEvents.EmailAddressChanged -= NotifyCustomerWhenEmailChanged; } }