public HttpResponseMessage ValidatePost([FromBody] FileUploadValidationModel model) { var command = new CreateFile(User) { FileData = new CreateFile.FileDataWrapper { FileName = model.Name, Content = model.Length.HasValue ? new byte[model.Length.Value] : new byte[0], }, }; var validationResult = _createValidator.Validate(command); var forProperties = new List<Func<ValidationFailure, bool>> { x => x.PropertyName == command.PropertyName(y => y.FileData.FileName), }; if (model.Length.HasValue) forProperties.Add(x => x.PropertyName == command.PropertyName(y => y.FileData.Content)); foreach (var forProperty in forProperties) if (validationResult.Errors.Any(forProperty)) return Request.CreateResponse(HttpStatusCode.BadRequest, validationResult.Errors.First(forProperty).ErrorMessage, "text/plain"); return Request.CreateResponse(HttpStatusCode.OK); }
public HttpResponseMessage Post(int agreementId, [FromBody] AgreementFileApiModel model) { model.AgreementId = agreementId; var command = new CreateFile(User) { FileData = model.FileMedium == null ? null : new CreateFile.FileDataWrapper { FileName = model.FileMedium.FileName, MimeType = model.FileMedium.ContentType, Content = model.FileMedium.Content, }, }; Mapper.Map(model, command); try { _createHandler.Handle(command); } catch (ValidationException ex) { Func<ValidationFailure, bool> forName = x => x.PropertyName == command.PropertyName(y => y.FileData.FileName); Func<ValidationFailure, bool> forContent = x => x.PropertyName == command.PropertyName(y => y.FileData.Content); if (ex.Errors.Any(forName)) return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, ex.Errors.First(forName).ErrorMessage, "text/plain"); if (ex.Errors.Any(forContent)) return Request.CreateResponse(HttpStatusCode.RequestEntityTooLarge, ex.Errors.First(forContent).ErrorMessage, "text/plain"); } var url = Url.Link(null, new { controller = "AgreementFiles", action = "Get", agreementId, fileId = command.CreatedFileId, }); Debug.Assert(url != null); var successPayload = new { message = string.Format("File '{0}' was successfully attached.", model.CustomName), location = url, // TODO: when IE8 dies, no need to do this (it is a workaround for kendo + IE only) }; var successJson = JsonConvert.SerializeObject(successPayload); var response = Request.CreateResponse(HttpStatusCode.Created, successJson, "text/plain"); response.Headers.Location = new Uri(url); return response; }