我想将如下所示的多部分表单数据发布到WEB API 2控制器。我的数据将包含JSON和Image文件。请帮助我理解c#api控制器代码如何用于以下数据。
目前我在Request.Content.ReadAsMultipartAsync(provider);
收到错误:
MIME多部分流的意外结束。 MIME多部分邮件不完整
var uploadPath = HttpContext.Current.Server.MapPath("~/Userimage/");
Directory.CreateDirectory(uploadPath);
var provider = new MultipartFormDataStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(provider);
// Files
//
foreach (MultipartFileData file in provider.FileData)
{
Debug.WriteLine(file.Headers.ContentDisposition.FileName);
Debug.WriteLine("File path: " + file.LocalFileName);
}
// Form data
//
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Debug.WriteLine(string.Format("{0}: {1}", key, val));
}
}
return Request.CreateResponse(HttpStatusCode.OK);
---------------------------acebdf13572468
Content-Disposition: form-data; name="modelclass"
Content-Type: application/json
{
"MessageID": 1,
"SenderID": 2,
"userType": "sample string 3",
"msgCategory": "sample string 4",
"msgContent": "sample string 5",
"msgDistributedTo": "sample string 6"
}
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="bg4.jpg"
Content-Type: image/jpeg
<@INCLUDE *C:\Users\Lenovo1\Pictures\bg4.jpg*@>
---------------------------acebdf13572468--
答案 0 :(得分:0)
几个月前我一直试图这样做,最后得到以下代码:
if (!request.Content.IsMimeMultipartContent("form-data"))
{
throw new InvalidOperationException("Media type not supported");
}
var root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
await request.Content.ReadAsMultipartAsync(provider);
您的代码可能存在的问题是您尝试创建应该已存在的目录。 请尝试在代码的开头进行内容类型检查。