FormData + IFormFile 为空

FormData + IFormFile is null

我在使用 IFormFile 和 FormData 时遇到问题。

当我使用 FormData 提交文件时,映射的对象 returns 在后端中为空值。

我提供了一个代码示例,以便您查看我的代码。

Angular:

upload(prod: Product) {
let formData = new FormData();

formData.append("productName", prod.productName);
formData.append("productSku", prod.productSku);    

for(let i=0;i<prod.variants.length;i++){
  formData.append(`variants[${i}][variantName]`, prod.variants[i].variantName);
  formData.append(`variants[${i}][media][fileName]`, prod.variants[i].media.fileName);
  formData.append(`variants[${i}][media][mediaFile]`, prod.variants[i].media.mediaFile);
}
console.log(prod);
this.http.post('https://localhost:7255/api/products', formData)
.subscribe(res => {
  console.log(res);
  alert('Uploaded Successfully.');
})

}

ASP.Net核心

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    
    public ProductsController() {}
    
    [HttpPost]
    public IActionResult Post([FromForm] ProductCreateDto product )
    {
        return Ok();
    }

}
public class ProductCreateDto
{
    [JsonProperty("productName")]
    public string? ProductName { get; set; }
    [JsonProperty("productSku")]
    public string? ProductSku { get; set; }
    [JsonProperty("variants")]
    public IEnumerable<Variant> Variants { get; set; }
}

public class Media
{
    [JsonProperty("fileName")]
    public string? FileName { get; set; }
    public IFormFile? MediaFile { get; set; }
}

public class Variant
{
    [JsonProperty("variantName")]
    public string? VariantName { get; set; }
    [JsonProperty("media")]
    public Media? Media { get; set; }
}

我得到了什么

当我更新代码并将 IFormFile 放入 DTO 时,它可以工作

    public class ProductCreateDto
{
    [JsonProperty("productName")]
    public string? ProductName { get; set; }
    [JsonProperty("productSku")]
    public string? ProductSku { get; set; }
    [JsonProperty("variants")]
    public IEnumerable<Variant> Variants { get; set; }
    
    public IFormFile TEST { get; set; }
}

第一个代码有什么错误?

我发现我的错误。映射不好。我之前检查过邮递员。如果有人感兴趣,这里是解决方案。

upload(prod: Product) {
    let formData = new FormData();

    formData.append("productName", prod.productName);
    formData.append("productSku", prod.productSku);    

    for(let i=0;i<prod.variants.length;i++){
      formData.append(`variants[${i}].variantName`, prod.variants[i].variantName);
      formData.append(`variants[${i}].media.fileName`, prod.variants[i].media.fileName);
      formData.append(`variants[${i}].media.mediaFile`, prod.variants[i].media.mediaFile);
    }   
    this.http.post('https://localhost:7255/api/products', formData)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }