I am sending multipart/form-data
to one of my action methods, because in addition to JSON I need to upload a file. So on the server side it looks like this:
public class ItemPostRequest
{
public List<Item> ItemsFromJson { get; set; }
public IFormFile File { get; set; }
}
public class Item
{
[Required]
public string Description { get; set; }
public string Amount { get; set; }
}
[HttpPost("test")]
public async Task<ActionResult<string>> PostItem([FromForm] ItemPostRequest itemPostRequest)
{
return Content("done", "application/json", System.Text.Encoding.UTF8);
}
And this is my request:
POST /api/items/test HTTP/1.1
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Postman-Token: 55378de0-71a2-4762-ae78-b6683917dbf4
Host: localhost:44376
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------087805821886130931238212
Content-Length: 899
----------------------------087805821886130931238212
// =============== THE RELEVANT PART STARTS HERE ====================
Content-Disposition: form-data; name="ItemsFromJson" // <======= important part
// <======= is
[{"Description":"my first item","Amount":"123"}] // <======= here
----------------------------087805821886130931238212
Content-Disposition: form-data; name="File"; filename="localhost-1610916507269.log"
<localhost-1610916507269.log>
----------------------------087805821886130931238212--
So, valid JSON is sent as ItemsFromJson
, but model binding is not working. Note in the following screenshot that ItemsFromJson.Count
is 0 though items were sent as [{"Description":"my first item","Amount":"123"}]
.
How can I get JSON deserialization and especially model validation when sending a multipart/form-data
request? I am aware that I could just create a string property in my ItemPostRequest
class and manually deserialize the JSON. But that would still be missing the model validation in the Item
class for the Description
property!?
public async Task<ActionResult<string>> PostItem([FromForm] ItemPostRequest itemPostRequest){}
topublic async Task<ActionResult<string>> PostItem([FromForm] string ItemsFromJson, IFormFile File){}
.Besides, you could also try to usevar filesToDelete = HttpContext.Request.Form["ItemsFromJson"]
to get the data from Form. – Zhi Lv Jan 26 at 8:45ModelBinder
– stefan.at.wpf Jan 26 at 19:40