Nota
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
En este artículo, ampliará la aplicación que creó en Compilación de aplicaciones .NET con Microsoft Graph y autenticación de solo aplicación con las API de usuario de Microsoft Graph. Use Microsoft Graph para enumerar los usuarios de su organización.
Abra ./GraphHelper.cs y agregue la siguiente función a la clase GraphHelper .
public static Task<UserCollectionResponse?> GetUsersAsync() { // Ensure client isn't null _ = _appClient ?? throw new System.NullReferenceException("Graph has not been initialized for app-only auth"); return _appClient.Users.GetAsync((config) => { // Only request specific properties config.QueryParameters.Select = new[] { "displayName", "id", "mail" }; // Get at most 25 results config.QueryParameters.Top = 25; // Sort by display name config.QueryParameters.Orderby = new[] { "displayName" }; }); }
Reemplace la función vacía
ListUsersAsync
en Program.cs por lo siguiente.async Task ListUsersAsync() { try { var userPage = await GraphHelper.GetUsersAsync(); if (userPage?.Value == null) { Console.WriteLine("No results returned."); return; } // Output each users's details foreach (var user in userPage.Value) { Console.WriteLine($"User: {user.DisplayName ?? "NO NAME"}"); Console.WriteLine($" ID: {user.Id}"); Console.WriteLine($" Email: {user.Mail ?? "NO EMAIL"}"); } // If NextPageRequest is not null, there are more users // available on the server // Access the next page like: // var nextPageRequest = new UsersRequestBuilder(userPage.OdataNextLink, _appClient.RequestAdapter); // var nextPage = await nextPageRequest.GetAsync(); var moreAvailable = !string.IsNullOrEmpty(userPage.OdataNextLink); Console.WriteLine($"\nMore users available? {moreAvailable}"); } catch (Exception ex) { Console.WriteLine($"Error getting users: {ex.Message}"); } }
Ejecute la aplicación y elija la opción 2 para enumerar a los usuarios.
Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 2 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: AdeleV@contoso.com User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: AlexW@contoso.com User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: AllanD@contoso.com User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: NO EMAIL User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: BrianJ@contoso.com ... More users available? True
Código explicado
Tenga en cuenta el código de la GetUsersAsync
función .
- Obtiene una colección de usuarios
-
Select
Usa para solicitar propiedades específicas -
Top
Usa para limitar el número de usuarios devueltos -
OrderBy
Usa para ordenar la respuesta