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

如何在C#中通过MultipartFormDataContent传递List<object>

解决MultipartFormDataContent发送int/自定义类列表为空的问题

你遇到的核心问题是没有为序列化后的JSON内容指定正确的Content-Type,或者API端期望的表单数据格式和你发送的不匹配。以下是两种可行的解决方式:

方式一:序列化后指定JSON内容类型

默认StringContent的Content-Type是text/plain,很多API框架无法自动将纯文本解析为JSON数组/对象列表。你需要显式指定application/json类型:

发送int列表示例

var multiForm = new MultipartFormDataContent();
var intList = new List<int> { 101, 102, 103 };
// 序列化int列表为JSON字符串
var intJson = JsonConvert.SerializeObject(intList);
// 显式指定编码和Content-Type为application/json
multiForm.Add(new StringContent(intJson, Encoding.UTF8, "application/json"), "intList");
// 其他字段...
multiForm.Add(new StringContent(testEmployee.UserID.ToString()), "UserID");

发送Employee自定义类列表示例

var multiForm = new MultipartFormDataContent();
var employeeList = new List<Employee> 
{ 
    new Employee { UserID = 1, Name = "Alice" },
    new Employee { UserID = 2, Name = "Bob" }
};
var empJson = JsonConvert.SerializeObject(employeeList);
multiForm.Add(new StringContent(empJson, Encoding.UTF8, "application/json"), "employees");

这种方式要求API端的接收模型支持从JSON字符串绑定到列表类型,比如ASP.NET Core中直接用[FromForm] List<Employee> employees配合JSON解析。

方式二:按表单数组格式逐个添加项

如果API端期望的是传统表单数组格式(而非JSON),你可以逐个添加列表中的元素,字段名遵循表单数组的命名规则:

发送int列表示例

var multiForm = new MultipartFormDataContent();
var intList = new List<int> { 101, 102, 103 };
// 逐个添加,字段名用`intList[]`(部分框架支持`intList`)
foreach (var num in intList)
{
    multiForm.Add(new StringContent(num.ToString()), "intList[]");
}

发送Employee自定义类列表示例

var multiForm = new MultipartFormDataContent();
var employeeList = new List<Employee> 
{ 
    new Employee { UserID = 1, Name = "Alice" },
    new Employee { UserID = 2, Name = "Bob" }
};

int index = 0;
foreach (var emp in employeeList)
{
    // 按索引绑定对象属性,字段名格式为`employees[index].PropertyName`
    multiForm.Add(new StringContent(emp.UserID.ToString()), $"employees[{index}].UserID");
    multiForm.Add(new StringContent(emp.Name), $"employees[{index}].Name");
    index++;
}

这种方式更贴近传统表单提交的格式,适合API端没有配置JSON表单绑定的场景。

额外检查点

  • 确认API端的接收模型属性名称和你发送的字段名完全匹配(大小写敏感取决于框架配置)
  • 如果用自定义类,确保类的属性有正确的访问修饰符(比如public),且无序列化异常
  • 可以用抓包工具对比成功的字符串列表请求和失败的int/Employee列表请求的差异,定位格式问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:10:17