You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET嵌套模型接收特殊命名文件时Attachments属性始终为空

问题描述

我希望接收带有特殊命名的文件,目前我的模型定义如下:

public class SampleResultModel : SampleResult
{
    public Dictionary<int, LayoutData> DataLayout { get; set; }
    .
    .
    .
}

public class LayoutData
{
    public int LayoutId { get; set; }
    public Dictionary<string, string> Data { get; set; }
    public Dictionary<string, string> Limits { get; set; }
    public Dictionary<string, IFormFile> Attachments { get; set; }
    public string DataType { get; set; }

    public LayoutData() { }
}

目前我能正常接收该结构下的所有字符串数据,但接收文件时,“Attachments”属性始终为null。

发送的数据如下:

dataLayout[0][layoutId]: 
1101
dataLayout[1][layoutId]: 
5
dataLayout[1][data][Conclusion]: 
dataLayout[1][data][Result]: 
1
dataLayout[0][Attachments][0]: 
(binary)
dataLayout[0][Attachments][1]: 
(binary)

我遗漏了什么?

编辑补充:
我还测试了以下定义:

public List<IFormFile> Attachments { get; set; }

结果仍为null;以及:

public class LayoutData
{
    public int LayoutId { get; set; }
    public Dictionary<string, string> Data { get; set; }
    public Dictionary<string, string> Limits { get; set; }
    public IFormFile Attachments { get; set; }
    public string DataType { get; set; }

    public LayoutData() { }
}

对应发送的数据:

dataLayout[0][layoutId]: 
1101
dataLayout[1][layoutId]: 
5
dataLayout[1][data][Conclusion]: 
dataLayout[1][data][Result]: 
1
dataLayout[0][attachments]: 
(binary)

但Attachments数据仍然为null...


解决方案

1. 确保请求Content-Type正确

上传文件必须使用multipart/form-data作为请求的Content-Type,普通的application/x-www-form-urlencoded无法携带二进制文件数据,这是文件绑定失败的常见原因。

2. 修正表单字段命名格式

ASP.NET Core的模型绑定对嵌套结构的字段命名有严格要求:

  • 若Attachments是Dictionary<string, IFormFile>,字段名需写成dataLayout[0].Attachments[自定义键名],而非dataLayout[0][Attachments][0];
  • 若Attachments是List<IFormFile>,需使用相同的字段名dataLayout[0].Attachments上传多个文件(同一个字段对应多个文件);
  • 若为单个IFormFile,字段名需与属性名严格匹配(默认绑定区分大小写,attachments和Attachments会被视为不同字段)。

3. 添加[FromForm]特性明确绑定源

在控制器Action的参数上添加[FromForm]特性,强制模型绑定从表单数据中读取值,避免自动绑定策略的歧义:

[HttpPost]
public IActionResult Submit([FromForm] SampleResultModel model)
{
    // 处理逻辑
    return Ok();
}

4. 优化模型结构(可选)

嵌套在Dictionary值中的IFormFile绑定支持有限,可考虑调整模型简化绑定:

public class LayoutData
{
    public int LayoutId { get; set; }
    public Dictionary<string, string> Data { get; set; }
    public Dictionary<string, string> Limits { get; set; }
    public List<IFormFile> Attachments { get; set; }
    public string DataType { get; set; }
}

对应表单字段命名为dataLayout[0].Attachments,上传多个文件时重复该字段即可。


内容的提问来源于stack exchange,提问作者Lukas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:01:28