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

ASP.NET Core接口返回空列表:调试有值浏览器显示为空

ASP.NET Core接口返回空列表问题解决

核心原因:JSON序列化无法访问私有字段

你的DomoticzDeviceStatus类中所有字段都是私有(_tblDomoticzDevice、_device_status、_timestamp),ASP.NET Core默认的JSON序列化器(无论是System.Text.Json还是Newtonsoft.Json)默认仅序列化公共属性,不会读取私有字段。这就导致调试时对象明明有值,但序列化后输出为空列表。

解决方案:将私有字段改为公共属性

修改DomoticzDeviceStatus类,把私有字段替换为带getter的公共属性,确保序列化器能访问到数据:

public class DomoticzDeviceStatus
{
    public TblDomoticzDevice TblDomoticzDevice { get; }
    public string DeviceStatus { get; }
    public string Timestamp { get; }

    public DomoticzDeviceStatus(TblDomoticzDevice tblDomoticzDevice, string device_status, string timestamp)
    {
        TblDomoticzDevice = tblDomoticzDevice;
        DeviceStatus = device_status;
        Timestamp = timestamp;
    }
}

如果想保留原有私有字段命名,也可以用属性封装私有字段:

public class DomoticzDeviceStatus
{
    private TblDomoticzDevice _tblDomoticzDevice;
    private string _device_status;
    private string _timestamp;

    public TblDomoticzDevice TblDomoticzDevice => _tblDomoticzDevice;
    public string DeviceStatus => _device_status;
    public string Timestamp => _timestamp;

    public DomoticzDeviceStatus(TblDomoticzDevice tblDomoticzDevice, string device_status, string timestamp)
    {
        _tblDomoticzDevice = tblDomoticzDevice;
        _device_status = device_status;
        _timestamp = timestamp;
    }
}

额外优化建议

  1. 避免重复反序列化
    你当前代码中每次都重复调用JsonConvert.DeserializeObject,可以只反序列化一次提升性能:
var responseContent = await response.Content.ReadAsStringAsync();
var jsonObj = (JObject)JsonConvert.DeserializeObject(responseContent);
var resultItem = jsonObj["result"][0];
domoticzDeviceStatuses.Add(new DomoticzDeviceStatus(
    domoticzDevice,
    resultItem["Data"].ToString(),
    resultItem["LastUpdate"].ToString()
));
  1. 使用依赖注入管理DbContext和HttpClient
    不要直接在方法内实例化KlevebrandContext,通过构造函数注入的方式获取,避免资源泄漏:
private readonly KlevebrandContext _dbContext;
private readonly HttpClient _client;

public YourController(KlevebrandContext dbContext, HttpClient client)
{
    _dbContext = dbContext;
    _client = client;
}

[HttpGet("GetDomoticzDevices")]
public async Task<List<DomoticzDeviceStatus>> GetAsync()
{
    var domoticzDeviceStatuses = new List<DomoticzDeviceStatus>();

    foreach(var domoticzDevice in await _dbContext.TblDomoticzDevices.ToListAsync())
    {
        var response = await _client.GetAsync($"http://10.0.0.11:8080/json.htm?type=devices&rid={domoticzDevice.Idx}");
        response.EnsureSuccessStatusCode(); // 确保请求有效,避免无效响应导致异常

        var responseContent = await response.Content.ReadAsStringAsync();
        var jsonObj = (JObject)JsonConvert.DeserializeObject(responseContent);
        var resultItem = jsonObj["result"][0];
        
        domoticzDeviceStatuses.Add(new DomoticzDeviceStatus(
            domoticzDevice,
            resultItem["Data"].ToString(),
            resultItem["LastUpdate"].ToString()
        ));
    }

    return domoticzDeviceStatuses;
}
  1. 添加空值检查避免异常
    如果Domoticz返回的result为空或没有索引0的元素,会抛出空引用异常,建议添加检查逻辑:
var resultArray = jsonObj["result"] as JArray;
if (resultArray != null && resultArray.Count > 0)
{
    var resultItem = resultArray[0];
    domoticzDeviceStatuses.Add(new DomoticzDeviceStatus(
        domoticzDevice,
        resultItem["Data"].ToString(),
        resultItem["LastUpdate"].ToString()
    ));
}
else
{
    // 处理无数据的情况,比如跳过该设备或记录日志
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:30:53