0

我正在发送multipart/form-data到我的一种操作方法,因为除了 JSON 之外,我还需要上传一个文件。所以在服务器端它看起来像这样:

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);
}

这是我的要求:

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--

因此,有效的 JSON 被发送为ItemsFromJson,但模型绑定不起作用。请注意,在以下屏幕截图中,ItemsFromJson.Count尽管项目以[{"Description":"my first item","Amount":"123"}]. 在此处输入图像描述

multipart/form-data发送请求时如何获得 JSON 反序列化,尤其是模型验证?我知道我可以在我的ItemPostRequest类中创建一个字符串属性并手动反序列化 JSON。但这仍然会缺少属性Item类中的模型验证Description!?

4

0 回答 0