简体   繁体   English

阅读MVC4 WebApi多部分数据

[英]Reading MVC4 WebApi Multipart Data

I'm sending multipart form-data to my WebApi controller. 我正在将多部分表单数据发送到我的WebApi控制器。 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). 我可以读取图像没问题,但无法弄清楚如何读取用户名部分(以andy作为值)。 It's not in the FormData property on the provider. 它不在提供程序的FormData属性中。 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. 您的provider变量应具有名为FormData的NameValueCollection属性。 You should therefore be able to do something like: 因此,您应该能够执行以下操作:

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

NB. NB。 I had to update my References to see the FormData property. 我不得不更新我的引用以查看FormData属性。 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. 我的RC版本是:Microsoft.AspNet.WebApi.Client.4.0.20505.0使用Nuget更新所有WebApi和MVC 4引用给了我Microsoft.AspNet.WebApi.Client.4.0.20710.0。

So I found what I think is probably a hacky way to do this: 所以我发现我认为这可能是一种hacky方式:

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

Is there a more-preferred way? 有更优选的方式吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM