You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在组织工作转派MVC应用中获取AAD成员并展示为下拉列表

How to Fetch AAD Members for a Work Assignment Dropdown in Your MVC App

Alright, since you already have your MVC app hooked up with AAD SSO and user authentication working smoothly, let's walk through how to pull all AAD members into a dropdown list for your work assignment flow. Here's a step-by-step breakdown tailored to your setup:

1. Add Required Microsoft Graph Permissions in AAD

First, your app needs permission to read all users in your AAD tenant. We'll use Microsoft Graph for this:

  • Go to your AAD App Registration → API Permissions → Add a permission
  • Select Microsoft Graph → Choose Application permissions (we want the app to access user data without requiring individual user consent)
  • Search for and select either User.Read.All (read all user profiles) or Directory.Read.All (broader access to directory objects, use if you need more than just user data later)
  • Click Add permissions, then don't forget to click Grant admin consent for [Your Tenant] (this is critical—without it, your app will get 403 errors when calling Graph)

2. Configure Microsoft Graph Client in Your MVC Project

Next, set up the Graph client to make API calls:

  • Install the necessary NuGet packages via Package Manager Console or NuGet Package Manager:
    Install-Package Microsoft.Graph
    Install-Package Microsoft.Identity.Web
    
  • Update your appsettings.json with your AAD and Graph configuration (fill in your tenant ID, client ID, and client secret):
    "AzureAd": {
      "Instance": "https://login.microsoftonline.com/",
      "Domain": "your-tenant-domain.onmicrosoft.com",
      "TenantId": "your-tenant-guid",
      "ClientId": "your-app-client-id",
      "ClientSecret": "your-app-client-secret",
      "CallbackPath": "/signin-oidc"
    },
    "GraphApi": {
      "BaseUrl": "https://graph.microsoft.com/v1.0",
      "Scopes": "https://graph.microsoft.com/.default"
    }
    
  • Register the Graph service in your startup code (for .NET 6+, this goes in Program.cs):
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddMicrosoftGraph(builder.Configuration.GetSection("GraphApi"))
        .AddInMemoryTokenCaches();
    

3. Fetch AAD Users in Your Controller

Now, inject the Graph client into your controller and pull the user data:

using Microsoft.Graph;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

public class WorkAssignmentController : Controller
{
    private readonly GraphServiceClient _graphServiceClient;

    // Inject GraphServiceClient via constructor
    public WorkAssignmentController(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }

    public async Task<IActionResult> AssignWork()
    {
        // Fetch all AAD users, selecting only the fields we need (ID and display name)
        var userPage = await _graphServiceClient.Users
            .Request()
            .Select(u => new { u.Id, u.DisplayName })
            .GetAsync();

        // Handle pagination (Graph returns 100 users per page by default)
        var allUsers = new List<User>();
        allUsers.AddRange(userPage.CurrentPage);
        while (userPage.NextPageRequest != null)
        {
            userPage = await userPage.NextPageRequest.GetAsync();
            allUsers.AddRange(userPage.CurrentPage);
        }

        // Convert to SelectListItem for the dropdown
        var assigneeList = allUsers.Select(u => new SelectListItem
        {
            Value = u.Id,
            Text = u.DisplayName
        }).OrderBy(item => item.Text).ToList();

        // Pass the list to the view via ViewBag
        ViewBag.Assignees = assigneeList;
        return View();
    }
}

4. Render the Dropdown in Your Razor View

Finally, add the dropdown to your view using either Razor syntax or Tag Helpers:

Option 1: Using Html.DropDownList

<div class="form-group mb-3">
    <label for="assigneeId" class="form-label">转派给:</label>
    @Html.DropDownList("AssigneeId", (IEnumerable<SelectListItem>)ViewBag.Assignees, "请选择组织成员", new { @class = "form-control" })
</div>
<div class="form-group mb-3">
    <label asp-for="AssigneeId" class="form-label">转派给:</label>
    <select asp-for="AssigneeId" asp-items="@(ViewBag.Assignees as IEnumerable<SelectListItem>)" class="form-control">
        <option value="">请选择组织成员</option>
    </select>
</div>

5. Troubleshooting Tips

  • If you get a 403 Forbidden error: Double-check that admin consent was granted for the Graph permissions, and that you're using application permissions (not delegated permissions)
  • If users aren't showing up: Verify your tenant ID and client secret are correct, and that you're selecting the right fields in the Graph API call
  • For large tenants: Pagination is important—don't skip the while loop to fetch all pages of users

内容的提问来源于stack exchange,提问作者subham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:10:52