简体   繁体   English

无法获取部门名称、经理名称并仅在 Microsoft Graph 中获取有限的用户响应 API C#

[英]Unable to get Department Name ,Manager Name and getting only limited users in response In Microsoft Graph API C#

I am using below code to get all the users from Active Directory:我正在使用以下代码从 Active Directory 获取所有用户:

     static async Task Main(string[] args)

    {
        int Flag = 0;


        //  var message = await result;

        try
        {


            var tenantId = "XXXXX.onmicrosoft.com";
            string searchCriteria = "";
            string searchString = "";

            string tokenUrl = $"https://login.microsoftonline.com/XXXXX.onmicrosoft.com/oauth2/v2.0/token";
            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            //I am Using client_credentials as It is mostly recommended
            tokenRequest.Content = new FormUrlEncodedContent(new System.Collections.Generic.Dictionary<string, string>
            {
                ["grant_type"] = "client_credentials",
                ["client_id"] = "XXX9",
                ["client_secret"] = "XXXXXX",
                ["scope"] = "https://graph.microsoft.com/.default"
            });

            dynamic json;
            AccessTokenClass results = new AccessTokenClass();


            //New Block For Accessing Data from Microsoft Graph Rest API
            HttpClient client = new HttpClient();
            var tokenResponse = await client.SendAsync(tokenRequest);
            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

            HttpClient _client = new HttpClient();

            string urlGraphUsers = "https://graph.microsoft.com/v1.0/users?$top=999";
            // odata_nextlink
            do
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format(urlGraphUsers));
                //Passing Token For this Request
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
                //unable to get department name in response

                HttpResponseMessage response = await _client.SendAsync(request);
                string responseBody = await response.Content.ReadAsStringAsync();

                dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());


                var apiResponse = await response.Content.ReadAsStringAsync();


                var data = JsonConvert.DeserializeObject<jsonModel>(apiResponse);
                urlGraphUsers = data.odata_nextLink;




                foreach (valueModel r in data.value.ToList())

                {
                   //Print all the fields ,but unable to get Reporting Manager name and Department 
                   Console.WriteLine(r.displayName);
                    Console.WriteLine(r.mail);
                }

                if (Flag == 0)
                {
                    await context.PostAsync($"No Search results found! Please Try again");

                }
            }
            while (urlGraphUsers != null);

        }


        catch
        {
            await context.PostAsync($"Unknown Exception Occurred. Unable to search results!");
            context.Done(true);
        }

        Console.WriteLine(Flag);
        Console.WriteLine("Flag");
        context.Done(true);

    }


     public class jsonModel
    {
        public string @odata_context { get; set; }
        public string @odata_nextLink { get; set; }
        public List<valueModel> value { get; set; }
    }
    public class valueModel
    {
        public List<string> businessPhones { get; set; }
        public string displayName { get; set; }
        public string givenName { get; set; }
        public string jobTitle { get; set; }
        public string mail { get; set; }
        public string mobilePhone { get; set; }
        public string officeLocation { get; set; }
        public string preferredLanguage { get; set; }
        public string surname { get; set; }
        public string userPrincipalName { get; set; }
        public string id { get; set; }
    }

I am unable to get Department name in response.Obviously something like r.departmentName doesn't work here.我无法在响应中获得部门名称。显然,像 r.departmentName 这样的东西在这里不起作用。

And i am only getting 100 users,even though i use odata.nextlink while loop.而且我只有 100 个用户,即使我在循环中使用 odata.nextlink。 This do while loop runs only one time and shows only 100 users.这个 do while 循环只运行一次并且只显示 100 个用户。 Value of data.odata_nextLink; data.odata_nextLink 的值; in the first loop itself is null.在第一个循环中本身就是 null。

How to fetch all the users using pagination and also department name and manager name or directReports.如何使用分页获取所有用户以及部门名称和经理名称或 directReports。 Please help, as i am beginner.请帮助,因为我是初学者。

As far as I know, the user just has property department but not departmentName , you can refer to this document .据我所知,用户只有属性department而没有departmentName ,你可以参考这个文档 在此处输入图像描述

In you code, when you do the "deserialize" operation, you need to let it know the odata_nextLink refers to @odata.nextLink field in json response.在您的代码中,当您执行“反序列化”操作时,您需要让它知道odata_nextLink引用 json 响应中的@odata.nextLink字段。 So please modify your code as below:所以请修改你的代码如下:

public class jsonModel
{
    [JsonProperty("@odata.context")]
    public string odata_context { get; set; }

    [JsonProperty("@odata.nextLink")]
    public string odata_nextLink { get; set; }

    public List<valueModel> value { get; set; }
}

After that, your code will work fine, the data.odata_nextLink will not be null.之后,您的代码将正常工作, data.odata_nextLink将不是 null。

Hope it helps~希望对你有帮助~

I recommend to leverage Microsoft .NET SDKs to avoid reinventing the wheel.我建议利用 Microsoft .NET SDK 来避免重新发明轮子。 This should work using Microsoft.Graph.Beta nuget package .这应该使用Microsoft.Graph.Beta nuget package工作。 This due MS Graph V1 not supporting user manager expands .这是由于 MS Graph V1 不支持用户管理器扩展

 private static async Task PrintUsersWithManager()
        {
            var app = ConfidentialClientApplicationBuilder.Create(clientId)
                .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
                .WithClientSecret(clientSecret)
                .Build();

            var token = await app.AcquireTokenForClient(new[] { ".default" }).ExecuteAsync();

            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async (message) =>
                    {
                        var result = await app.AcquireTokenForClient(new[] { ".default" }).ExecuteAsync();
                        message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
                    }
                    )
                );

            var page = await graphServiceClient.Users.Request()
                .Expand(u => u.Manager)
                .GetAsync();

            var users = new List<User>();

            users.AddRange(page);

            while (page.NextPageRequest != null)
            {
                page = await page.NextPageRequest
                    .Expand(u => u.Manager)
                    .GetAsync();

                users.AddRange(page);
            }

            foreach (var item in users)
            {
                Console.WriteLine(JsonConvert.SerializeObject(new
                {
                    item.Id,
                    item.DisplayName,
                    item.Department,
                    Manager = item.Manager != null ? new
                    {
                        item.Manager.Id,
                        displayName = ((User)item.Manager).DisplayName
                    } : null
                }));
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 Microsoft Graph API C# 代码获取部门名称、经理等 - Unable to get Department Name , Manager etc using Microsoft Graph API C# Code C# 中的 Microsoft Graph api 代码仅显示有限数量的用户 - Microsoft Graph api code in C# displays only limited number of users Microsoft Graph API 获取用户源名称(提供者名称)? - Microsoft Graph API get users Source name (Provider name)? 仅获取具有 TransitiveMembers Microsoft Graph C# SDK 的用户 - Get only users with TransitiveMembers Microsoft Graph C# SDK 如何在 c# Microsoft graph api 请求中获得响应 header - How to get response header in c# Microsoft graph api request 使用 Microsoft Graph API V1.0 时匹配部门名称的问题 - Issue in Matching Department Name while using Microsoft Graph API V1.0 无法从 IUserPeopleCollectionPage 类型 Dataa MS Graph API 中找到部门名称 - Unable to find department name from IUserPeopleCollectionPage type Dataa MS Graph API 使用C#需要当前组织中的所有用户详细信息(姓名,电子邮件,指定,部门) - Need all users detail (Name, Email, Designation, Department) in the current organisation using C# Microsoft Graph API无法发送电子邮件C#控制台 - Microsoft Graph API unable to Send Email C# Console 无法通过 Microsoft Graph API(C# 控制台)发送电子邮件 - Unable to send email via Microsoft Graph API (C# Console)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM