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 =>
{
...
}
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With