I have a asp web api Post method in controller with model that can handle json object and files together
This is the POST method:
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");
}
and here is the 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) {...}
In the middleware that handles the multipart request I see tvo items in the stream, the json object itself with content-type: application/json and I see the file with content-type = application/octet-stream.
But it always crashes with modelstate error, saying that:
{"message":"The request is invalid.","modelState":{"email":["The email field is required."]}}
How can I upload to request object to the controller and have it recognize that one of the item is the datamodel "email" ?