IFormFile 作为嵌套的 ViewModel 属性

Gra*_*han 7 c# .net-core asp.net-core

我正在尝试使用 IFormFile 作为嵌套 ViewModel 中的属性。我在尝试在运行时将 ViewModel 绑定到控制器操作时遇到了问题。AJAX 请求停止并且永远不会到达操作。

这个概念性问题参考了我在 .NET Core ViewModel中的IFormFile 属性中导致停滞的 AJAX 请求的特定问题

视图模型:

public class ProductViewModel
{
    public ProductDTO Product { get; set; }
    public List<ProductImageViewModel> Images { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

嵌套视图模型:

public class ProductImageViewModel
{
    public ProductImageDTO ProductImage { get; set; }
    public IFormFile ImageFile { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

行动:

[HttpPost]
public IActionResult SaveProduct([FromForm]ProductViewModel model)
{
    //save code
}
Run Code Online (Sandbox Code Playgroud)

我想知道 IFormFile 属性是否需要是您绑定到控制器操作的 ViewModel 的直接属性

IFormFile文档似乎并没有回答我的问题。

itm*_*nus 9

AJAX 请求停止并且永远不会到达操作。

这是一个已知问题,已修复,v3.0.0-preview不会合并到2.2.x分支中。见#4802

当发布与形式IList<Something> Something,其中Something 具有的属性IFormFile直接,它会导致一个无限循环。因为模型绑定发生在调用 action 方法之前,你会发现它永远不会进入 action 方法。此外,如果您检查任务管理器,您会发现内存使用情况很疯狂。

要绕过它,正如@WahidBitar所建议的那样,只需在 上创建一个包装器,IFormFile这样Something就没有IFormFile直接的 .

至于你的问题本身,改变你的代码如下:

    公共类 ProductViewModel
    {
        公共产品DTO产品{得到; 放; }
        公共列表<ProductImageViewModel> 图像 { 获取;放; }
    }


    公共类 ProductImageViewModel
    {
        公共 ProductImageDTO ProductImage { 获取;放; }
        // 因为这个 ProductImageViewModel 将被嵌入为 List<ProductImageViewModel> 
        //直接
        确保它没有 IFormFile 属性public IFormFile ImageFile { get; 放; } 
        public IFormFileWrapper Image{ get; 放; }  

        // 一个虚拟包装器
        公共类 IFormFileWrapper 
        {
            公共 IFormFile 文件 { 获取;设置;} 
        }
    }

现在您的客户端应该将字段名称重命名如下:

Images[0].ProductImage.Prop1     # Your DTO prop's
Images[0].Image.File             # instead of Images[0].ImageFile
Images[0].ProductImage.Prop2     # Your DTO prop's
Images[1].Image.File             # instead of Images[1].ImageFile
...                              # other images
Product.Prop1
Product.Prop2
...                              # other props of Product
Run Code Online (Sandbox Code Playgroud)

一个工作演示:

在此处输入图片说明