.NET 5 API接收嵌套List时内层List始终为null的问题咨询
问题排查与解决方案
嘿,我刚好碰到过类似的.NET Framework到.NET 5的迁移问题,来给你理一理:.NET 5完全支持嵌套List的传递,问题出在JSON序列化器的配置差异上。
核心原因
你的实体类用了[DataContract]和[DataMember]特性,这些是WCF时代DataContractSerializer的标记。在.NET Framework 4.8的Web API中,默认使用的是Newtonsoft.Json(Json.NET),它能识别这些特性;但.NET 5默认改用了System.Text.Json作为JSON序列化器,而它默认不支持[DataContract]/[DataMember]特性,导致内层List的属性没有被正确映射,最终出现null的情况。
解决方法(两种可选)
方法一:切换回Newtonsoft.Json(最省心,和旧行为完全一致)
- 先安装NuGet包:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson - 在
Startup.cs的ConfigureServices方法中配置:public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); // 替换默认的System.Text.Json }
这样不需要修改任何实体类代码,就能和.NET Framework时代一样正常接收嵌套List了。
方法二:适配System.Text.Json的特性规范
如果想保留.NET 5默认的序列化器,可以修改实体类的特性,改用System.Text.Json支持的标记:
- 直接移除
[DataContract]和[DataMember](System.Text.Json默认会匹配属性名的大小写,你的请求体和属性名完全一致,甚至不需要额外配置) - 如果需要严格指定JSON属性名,可以用
[JsonPropertyName]标记
修改后的实体类示例:
public class TestClass { public string Name { get; set; } public List<TestClassArray> Related1 { get; set; } } public class TestClassArray { public string id1 { get; set; } public List<TestClassArray2> Related2 { get; set; } } public class TestClassArray2 { public string id2 { get; set; } }
额外方案:让System.Text.Json支持DataContract特性(不推荐,较繁琐)
如果你不想修改实体类也不想换序列化器,可以通过自定义配置让System.Text.Json识别[DataContract]:
services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { static typeInfo => { if (typeInfo.Kind == JsonTypeInfoKind.Object) { foreach (var property in typeInfo.Properties) { var dataMemberAttr = property.AttributeProvider .GetCustomAttributes(typeof(DataMemberAttribute), false) .FirstOrDefault() as DataMemberAttribute; if (dataMemberAttr != null) { property.Name = dataMemberAttr.Name ?? property.Name; property.IsRequired = dataMemberAttr.IsRequired; } } } } } }; });
验证测试
修改完成后,用你的测试请求体再次调用接口,内层的Related2 List就能被正常反序列化了。
内容的提问来源于stack exchange,提问作者Geo
相关产品推荐
相关产品推荐

