[英].net core 2.1 "POST" an IFormFile using Postman - the application completed without reading the entire request body
[英]Postman POST request Model binding not working with an IFormfile property
我有一個像這樣的 model。
public class ClientDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public IFormFile ProfilePicture { get; set; }
}
和 API controller 這樣的:
[HttpPost]
public async Task<OperationResult> Post([FromForm] ClientDto c)
{
ImageHandler handler = new ImageHandler(env);
Client client = new Client()
{
Address = c.Address,
FirstName = c.FirstName,
LastName = c.LastName,
PhoneNumber = c.PhoneNumber,
PhotoPath = await handler.UploadFile(c.ProfilePicture)
};
return await clientRepository.AddClient(client);
}
現在,如果我在包含一個以ProfilePicture
作為鍵的文件(在Postman >> Body >> form-data 部分下)后使用 postman 發出Post
請求,model 綁定將按預期工作。 api controller 接收PofilePicture
和 rest 屬性null
。 但是,如果我將 json 字符串用於類似這樣的其他屬性(在 Postman >> Body >> raw部分下)
{
"c":{
"FirstName": "XYZ",
"LastName":"ABX"
}
}
或者
{
"FirstName": "XYZ",
"LastName":"ABX"
}
model 綁定不再有效。 如果我想提供所有屬性,如何使用 postman 擊中 api controller?
您正在混合發送到 controller 的數據 - 它很混亂。
在您對圖像的請求中,內容類型是multipart/form-data
,因為正文包含一個文件和可能的其他表單數據字段。 在帶有 JSON 的請求中,內容類型是application/json
並且您沒有發送任何文件數據。
您必須決定僅發送 JSON 或表單數據。
在這種情況下,由於您要發送文件,因此您需要使用multipart/form-data
並只需在 Postman 的表單字段中設置缺少的字段( 請參閱此處如何設置 Postman 表單數據參數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.