Blazor调用Battlemetrics API获取maxPlayers值异常问题排查
问题排查与修复
核心错误原因
BattleMetrics的该API返回数据是嵌套结构,并非直接返回Attributes对象。你的代码直接用Attributes接收整个响应,导致无法正确映射maxPlayers字段,而int类型默认值为0,所以最终显示结果为0。
API返回的简化结构如下:
{ "data": { "type": "server", "id": "20151421", "attributes": { "maxPlayers": 200, // 其他字段... } } }
修复步骤
1. 补充匹配API结构的模型类
需要新增两个包装类来适配嵌套结构:
// 根响应类 public class ServerResponse { public ServerData Data { get; set; } } // 数据层包装类 public class ServerData { public Attributes Attributes { get; set; } } // 原Attributes类保持不变 public class Attributes { public string id { get; set; } public string name { get; set; } public string address { get; set; } public string ip { get; set; } public int port { get; set; } public int players { get; set; } public int maxPlayers { get; set; } public int rank { get; set; } public List<double> location { get; set; } public string status { get; set; } public Details details { get; set; } public bool @private { get; set; } public DateTime createdAt { get; set; } public DateTime updatedAt { get; set; } public int portQuery { get; set; } public string country { get; set; } public string queryStatus { get; set; } } // 补充Details类(根据API返回的details字段内容添加对应属性) public class Details { // 示例属性,按需添加: // public string game { get; set; } }
2. 修改数据获取逻辑
调整接口调用代码,先接收完整响应,再提取目标Attributes数据:
public async Task FetchData() { var response = await httpClient.GetFromJsonAsync<ServerResponse>("https://api.battlemetrics.com/servers/20151421"); todo = response?.Data?.Attributes; }
3. 优化HttpClient使用(可选但推荐)
Blazor中推荐通过依赖注入获取HttpClient,避免直接实例化导致的资源问题:
// 替换原有的HttpClient实例化代码 [Inject] public HttpClient HttpClient { get; set; }
内容的提问来源于stack exchange,提问作者quaka
相关产品推荐
相关产品推荐

