.NET 8 Blazor WebAssembly API返回列表Count显示0但实际有元素
Blazor WebAssembly反序列化List后Count显示0但实际含元素的排查与解决
针对你遇到的问题,结合代码和API返回内容,以下是具体的排查方向和解决步骤:
1. 修复反序列化大小写不匹配问题
System.Text.Json默认区分大小写,而API返回的JSON属性为小写(如success、data),但你的ApiResponse<T>类属性是大写开头(Success、Data),这会导致属性映射失败,最终出现Data看似为空但实际有内容的矛盾现象。
修改HandleResponse扩展方法,添加不区分大小写的序列化配置:
public static async Task<ApiResponse<T>> HandleResponse<T>(this HttpResponseMessage response) { if (response.IsSuccessStatusCode) { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true // 开启大小写不敏感匹配 }; return await response.Content.ReadFromJsonAsync<ApiResponse<T>>(options) ?? new ApiResponse<T> { Success = false }; } return new ApiResponse<T> { Success = false, Message = "API call failed", Errors = new List<string> { response.ReasonPhrase } }; }
2. 验证TreatmentDto的属性映射
确保TreatmentDto的属性与JSON字段完全匹配,若字段名大小写或命名风格不同(如JSON的isMuted对应类的IsMuted),需添加JsonPropertyName特性显式绑定:
public class TreatmentDto { [JsonPropertyName("id")] public Guid Id { get; set; } [JsonPropertyName("type")] public int Type { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("isMuted")] public bool IsMuted { get; set; } // 其他属性同理添加JsonPropertyName特性 }
3. 确认反序列化结果的真实性
避免依赖调试器的可能异常显示,在代码中直接输出结果验证:
var response = await GetTreatmentsAsync(); Console.WriteLine($"请求是否成功:{response.Success}"); Console.WriteLine($"数据列表Count:{response.Data?.Count ?? -1}"); if (response.Data != null) { foreach (var treatment in response.Data) { Console.WriteLine($"治疗项名称:{treatment.Name}"); } }
4. 检查嵌套集合的映射
若TreatmentDto内部的集合属性(如expectedUnits、reminders)也出现类似问题,同样需要检查其对应的实体类是否添加了正确的属性绑定配置,确保嵌套结构的反序列化正常。
内容的提问来源于stack exchange,提问作者Jesse Coble
相关产品推荐
相关产品推荐

