azure Microsoft Graph .NET Core SDK:突然施法错误

czfnxgou  于 2023-08-07  发布在  .NET
关注(0)|答案(1)|浏览(99)

我正在使用Microsoft Graph .NET Core SDK获取当前用户所属的所有AAD组。其中参数“name”为UPN

public List<string> GetUserGroups(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            
            var groups = new List<string>();
            var userGroups = _graphServiceClient.Users[name].MemberOf.Request().GetAsync().Result;
            bool hasNextPage;
           
            do
            {
                hasNextPage = userGroups.NextPageRequest != null;
                groups.AddRange(userGroups.CurrentPage.Cast<Group>().Select(x => x.DisplayName));

                if (hasNextPage)
                {
                    userGroups = userGroups.NextPageRequest.GetAsync().Result;
                }
            }
            while (hasNextPage);

            return groups;
        }

字符串
这段代码一直工作得很好,直到最近,任何获取组信息的尝试都以InvalidCastException结束:
Unable to cast object of type 'Microsoft.Graph.AdministrativeUnit' to type 'Microsoft.Graph.Group'.
我的代码甚至没有访问要强制转换的AdministrativeUnit。我没有改变任何代码,所以我不知道这里发生了什么。

w8biq8rn

w8biq8rn1#

您可以通过将段microsoft.graph.group附加到请求URL来应用OData转换。

public List<string> GetUserGroups(string name)
{
    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }
        
    var groups = new List<string>();
    var requestUrl = _graphServiceClient.Users[name]             
                       .MemberOf
                       .AppendSegmentToRequestUrl("microsoft.graph.group");
    var userGroups = new GraphServiceGroupsCollectionRequest(requestUrl, _graphServiceClient, Enumerable.Empty<Option>())
            .GetAsync().Result;
    bool hasNextPage;
       
    do
    {
        hasNextPage = userGroups.NextPageRequest != null;
        groups.AddRange(userGroups.CurrentPage.Cast<Group>().Select(x => x.DisplayName));

        if (hasNextPage)
        {
            userGroups = userGroups.NextPageRequest.GetAsync().Result;
        }
    }
    while (hasNextPage);

    return groups;
}

字符串

相关问题