我在控制器中有一个ASP Web API Post方法,其模型可以一起处理json对象和文件
这是POST方法:
public async Task<IHttpActionResult> PostAsync([Required]Models.Email email, CancellationToken token = default(CancellationToken))
{
if (multipartContentProvider.IsMultipartRequest)
//manages the file upload..
}
return Content(HttpStatusCode.Created, "uploaded");
}
这是JavaScript:
var formdata = new FormData();
//the file
formData.append('userpic', myFileInput.files[0], 'chris.jpg');
the json object
formData.append('email', new Blob([JSON.stringify({
subject: "hello there",
description: "this is a text"
})], {
type: "application/json"
}));
fetch(url, {
method: 'POST',
body: formData,
headers: {
}
}).then(function (response) {
if (response.status === 404) {
console.log("that did not work :(");
return;
}
return response.json();
}).then(function (data) {...}
在处理多部分请求的中间件中,我看到流中有tvo项,内容类型为application / json的json对象本身,并且内容类型为application / octet-stream的文件。
但是它总是因模型状态错误而崩溃,说:
{“ message”:“请求无效。”,“ modelState”:{“ email”:[“电子邮件字段为必填。”]}}
如何上载请求对象到控制器并使其识别出其中一项是数据模型“电子邮件”?