Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading MVC4 WebApi Multipart Data

I'm sending multipart form-data to my WebApi controller. The content I'm interested in includes both an image and another non-image value. I can read the image no problem, but can't figure out how to read the username part (with andy as the value). It's not in the FormData property on the provider. How can I get it?

Multi-part Form Data

------------ei4KM7KM7ae0GI3Ef1gL6ei4ae0ae0
Content-Disposition: form-data; name="Filename"

image.jpg
------------ei4KM7KM7ae0GI3Ef1gL6ei4ae0ae0
Content-Disposition: form-data; name="username"

andy
------------ei4KM7KM7ae0GI3Ef1gL6ei4ae0ae0
Content-Disposition: form-data; name="Filedata"; filename="image.jpg"
Content-Type: application/octet-stream


------------ei4KM7KM7ae0GI3Ef1gL6ei4ae0ae0
Content-Disposition: form-data; name="Upload"

Submit Query
------------ei4KM7KM7ae0GI3Ef1gL6ei4ae0ae0--

Controller Code

string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);

var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(o =>
{ 
    ...
}
like image 352
sewershingle Avatar asked Aug 20 '12 04:08

sewershingle


2 Answers

There is a good article on this here

Your provider variable should have a NameValueCollection property called FormData. You should therefore be able to do something like:

string username = provider.FormData.GetValues("username").SingleOrDefault();

NB. I had to update my References to see the FormData property. My version of RC was: Microsoft.AspNet.WebApi.Client.4.0.20505.0 using Nuget to update all WebApi and MVC 4 references gave me Microsoft.AspNet.WebApi.Client.4.0.20710.0.

like image 54
Mark Jones Avatar answered Sep 21 '22 14:09

Mark Jones


So I found what I think is probably a hacky way to do this:

string username = provider.Contents.First(x=>x.Headers.ContentDisposition.Name == "\"username\"").ReadAsStringAsync().Result;

Is there a more-preferred way?

like image 32
sewershingle Avatar answered Sep 21 '22 14:09

sewershingle