Graph SDK v5中如何获取含ContentType的Drive items并过滤?
在Microsoft Graph SDK v5中获取Drive Item的ContentType并过滤
Graph SDK v5默认不会返回ContentType这类关联资源,必须显式通过Expand方法指定加载该属性——这是v5相较于v4的关键差异(v4部分场景默认返回关联属性,v5则严格遵循Graph API的默认行为)。
解决步骤
- 在请求中添加
Expand配置,告知Graph API需要返回Drive Item关联的ContentType信息 - 过滤逻辑中增加空值判断,避免触发
NullReferenceException
修改后的完整代码
// 获取站点的driveId var driveItem = await graphClient.Sites[siteId].Drive.GetAsync(); var siteDriveId = driveItem.Id; // 加载drive items并显式展开ContentType var allDocs = await graphClient.Drives[siteDriveId].Items .GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Expand = new string[] { "contentType" }; }); // 过滤时增加空值判断 var files = allDocs.Value.Where(d => d.ContentType != null && !d.ContentType.Name.ToLower().Equals("customfolder") && !d.ContentType.Name.ToLower().Equals("folder"));
替代方案(沿用v4类似的列表项路径)
如果你习惯v4中从站点列表项获取的方式,也可以直接调用站点驱动器对应的列表项接口,同样需要展开ContentType:
var allDocs = await graphClient.Sites[siteId].Drives[driveId].List.Items .GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Expand = new string[] { "contentType" }; }); var files = allDocs.Value.Where(d => d.ContentType != null && !d.ContentType.Name.ToLower().Equals("customfolder") && !d.ContentType.Name.ToLower().Equals("folder"));
内容的提问来源于stack exchange,提问作者Jussi Palo
相关产品推荐
相关产品推荐

