C#使用multipart/form-data提交数组字段报properties应为array却为null错误
问题原因
- 手动拼接JSON格式非法:字符串类型的
propertyValue值未加双引号,拼接后生成的内容不符合JSON语法规范,服务端解析JSON失败,最终将字段值转为null。 - 传参方式不匹配服务端预期:部分服务端校验逻辑要求
multipart/form-data直接传递数组结构的字段,而非将整个数组序列化为JSON字符串作为单个字段提交,即使JSON格式正确也会被识别为非数组类型。
解决方案
方案1:服务端预期接收JSON序列化的数组字符串
不要手动拼接JSON,使用成熟的JSON序列化库生成标准JSON,避免格式错误:
- 首先定义对应的数据模型:
public class PropertyItem { public string propertyName { get; set; } public string propertyValue { get; set; } public string propertyLabel { get; set; } }
- 序列化后提交:
var properties = new List<PropertyItem> { new PropertyItem { propertyName = "email", propertyValue = email, propertyLabel = "Email" }, new PropertyItem { propertyName = "firstName", propertyValue = firstName, propertyLabel = "First Name" }, new PropertyItem { propertyName = "lastName", propertyValue = lastName, propertyLabel = "Last Name" } }; // 使用System.Text.Json序列化 string fields = System.Text.Json.JsonSerializer.Serialize(properties); // 若使用Newtonsoft.Json则替换为: // string fields = Newtonsoft.Json.JsonConvert.SerializeObject(properties); multiContent.Add(new StringContent(fields, System.Text.Encoding.UTF8, "application/json"), "properties");
方案2:服务端预期接收原生multipart数组结构
按照multipart表单数组的提交规范,逐个添加数组元素:
// 直接使用你提供的Item类 var items = new List<Item> { new Item { name = "email", value = email }, new Item { name = "firstName", value = firstName }, new Item { name = "lastName", value = lastName } }; // 按索引提交数组 for(int i =0; i< items.Count; i++) { multiContent.Add(new StringContent(items[i].name), $"properties[{i}].name"); multiContent.Add(new StringContent(items[i].value), $"properties[{i}].value"); } // 若服务端仅识别无索引的数组格式,可替换为: // foreach(var item in items) // { // multiContent.Add(new StringContent(item.value), "properties[]"); // }
内容的提问来源于stack exchange,提问作者Stavrogin
相关产品推荐
相关产品推荐

