2

How can i upload file and model parameters in mvc WEB API 2.

I have following code, which works just fine, if i remove model from the action, but with the model, I am receiving following error.

"message": "The request entity's media type 'multipart/form-data' is not supported for this resource.", "exception_message": "No MediaTypeFormatter is available to read an object of type 'CreateTicketDTO' from content with media type 'multipart/form-data'.",

 [HttpPost]
 [Route("api/support/tickets/")]
        public async Task<HttpResponseMessage> Insert(CreateTicketDTO dto)
        {
           if(dto == null)
                return Request.CreateResponse(HttpStatusCode.BadRequest, "Please supply required parameters");


            var provider = new MultipartMemoryStreamProvider();
            var a = await Request.Content.ReadAsMultipartAsync(provider);
            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var buffer = await file.ReadAsByteArrayAsync();
                //Do whatever you want with filename and its binaray data.
            }

            using (_ticketService)
            {
                var ticket = await _ticketService.CreateNewTicket(dto);

                return Request.CreateResponse(HttpStatusCode.OK, ticket);
            }
        }

I am creating a post request in Postman.

Robert
  • 2,971
  • 4
  • 27
  • 45
  • change media type from multipart/form-data to application/x-www-form-urlencoded – Andrey Ischencko Jun 23 '16 at 14:10
  • that produces following error: Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'.\r\nParameter name: content", – Robert Jun 23 '16 at 14:12
  • http://stackoverflow.com/questions/28369529/how-to-setup-a-webapi-controller-for-multipart-form-data – Venky Jun 23 '16 at 14:15
  • @venky, there is no example with model+file in this thread. – Robert Jun 23 '16 at 14:29
  • `string root = HttpContext.Current.Server.MapPath("~/App_Data");` `var provider = new MultipartMemoryStreamProvider(root);` may it work. – Venky Jun 23 '16 at 14:36
  • http://stackoverflow.com/questions/23729458/webapi-method-that-takes-a-file-upload-and-additional-arguments – Venky Jun 23 '16 at 14:38
  • @Venky, my file upload works just fine, but i have a problem with binding file and DTO model at the same time in my action. – Robert Jun 23 '16 at 14:45
  • I think the last SO link i shared deals with the similar issue. It suggests to create formatter which wraps the DTO inside it to be able to pass to HTTP. – Venky Jun 23 '16 at 14:46

0 Answers0