Sending model along with uploading files

Asked

Viewed 618 times

6

I have a web API built with ASP.NET Webapi, I have a model that references a file URI (for example representing a photo in a photo gallery, or a product in a catalog) and I need to send the data to the API.

Regarding to upload the file I have already managed to find out how this is done in Webapi on the Asp.net website itself, the problem is that the default Binder model does not work when the form is sent with enctype=multipart/form-data.

What I mean is that I have in the controller a method with this signature:

public async Task<IHttpActionResult> Post([FromBody] Model model)

If I don’t send with enctype=multipart/form-data The Binder model works and I can recover the model data, but I don’t get the file. If I put this, I get the file but the Binder model throws an exception

The request Entity’s media type 'Multipart/form-data' is not supported for this Resource.

No Mediatypeformatter is available to read an Object of type 'Model' from content with media type 'Multipart/form-data'.

The only solution I thought about for now was basically to send only the model in a request first, then in a separate request send the file and associate the URI in the model.

Is there any way to do both at the same time? Or the most common is to actually do it in two steps, first by sending the model and then the file?

2 answers

1

I don’t know the version you are using of Asp.Net, but try to get the file by request:

   if (Request.Files.Count > 0)
   {
                if (!String.IsNullOrEmpty(Request.Files[0].FileName))
                {   
                   //ROTINA PARA VALIDAR E SALVAR O ARQUIVO
                }
  }

0

You should use the multipar/form-data enctype yes, but your action should not have a method, you will have to do the handling of the values in hand, through a foreach loop on MultipartFormDataStreamProvider.FormData.AllKeys, if it is necessary to actually map the form data to an object (model) you can do this using Reflection

See if this link helps you:

https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.