Graph Beta C#调用获取Win32LobApp及检测规则等字段为空问题
问题排查与修复方案
核心问题分析
你的代码返回结果仅_createdOn有值、其他字段为空,主要源于三个关键问题:
- 未展开检测规则属性:Graph API默认不返回嵌套的
detectionRules属性,你只在请求中展开了assignments,未包含detectionRules,导致win32LobApp.DetectionRules为空集合,循环逻辑根本不会执行。 - 分配ID收集逻辑错误:
idsFromAssignment是全局列表,未在每个应用循环时清空,会导致所有应用的分配ID混在一起;同时若SDK未正确加载assignments,也会直接返回空值。 - 未指定需返回的字段:Graph SDK默认仅返回资源基础属性,需显式指定
$select来获取你需要的字段(如createdDateTime、检测规则相关属性等)。
修复步骤
1. 修正请求参数,同时展开嵌套属性
在请求配置中,同时将assignments和detectionRules加入Expand数组,并通过Select指定必要字段,确保需要的数据被返回。
2. 修复分配ID收集逻辑
每个应用单独创建分配ID列表,避免跨应用的数据污染。
3. 安全处理类型转换
改用is/as关键字进行类型判断与转换,避免强制转换引发的异常。
修复后的完整代码
public async Task<List<GraphResponseModel>> GetAllWin32LobAppWithDetectionRules() { try { List<GraphResponseModel> graphResponseModelList = new(); // 获取所有Win32LobApp,同时展开assignments和detectionRules,指定需返回的字段 var mobileApps = await _graphClient.DeviceAppManagement.MobileApps.GetAsync(context => { context.QueryParameters.Filter = "isof('microsoft.graph.win32LobApp')"; context.QueryParameters.Expand = new string[] { "assignments", "detectionRules" }; // 按需添加需要的字段 context.QueryParameters.Select = new string[] { "id", "createdDateTime", "displayName" }; context.QueryParameters.Top = 1000; // 与Postman保持一致的分页大小 }); foreach (var mobileApp in mobileApps.Value) { // 安全转换为Win32LobApp,跳过非目标类型的应用 var win32LobApp = mobileApp as Win32LobApp; if (win32LobApp == null) continue; // 收集当前应用的分配ID,空值保护避免异常 List<string?> idsFromAssignment = mobileApp.Assignments?.Select(a => a.Id).ToList() ?? []; // 遍历检测规则,空值保护避免循环空集合 foreach (var detection in win32LobApp.DetectionRules ?? Enumerable.Empty<Win32LobAppDetection>()) { if (detection is Win32LobAppRegistryDetection registryDetection) { var detectionRulesModel = new DetectionRulesModel( registryDetection.OdataType, registryDetection.Check32BitOn64System ?? false, registryDetection.KeyPath, registryDetection.ValueName, registryDetection.DetectionType?.Value.ToString() ?? string.Empty, registryDetection.Operator?.ToString() ?? string.Empty, registryDetection.DetectionValue ); var createdOn = win32LobApp.CreatedDateTime?.DateTime ?? DateTime.MinValue; graphResponseModelList.Add(new GraphResponseModel(idsFromAssignment, detectionRulesModel, createdOn)); } } } return graphResponseModelList; } catch (Exception e) { Console.WriteLine(e); throw; } }
额外注意事项
- 确保Graph API权限足够:需要
DeviceManagementApps.Read.All或更高权限。 - 分页处理:若Win32应用数量超过1000,需检查
mobileApps.OdataNextLink并循环获取下一页数据。 - 空值处理:所有可能为null的属性都添加了空值保护,避免空引用异常。
内容的提问来源于stack exchange,提问作者Gluhaia_Muha
相关产品推荐
相关产品推荐

