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

ASP.NET Core 7调用Microsoft Graph API获取用户信息的配置问题求助

ASP.NET Core MVC调用Microsoft Graph获取当前用户信息问题修复

问题分析

启动失败的核心原因是DI容器中未注册IConfidentialClientApplication服务,导致GraphService无法被构造。除此之外,代码还存在以下不合理之处:

  • 使用AcquireTokenForClient(客户端凭证流)获取令牌,该流用于服务对服务的调用,无法通过/me端点获取当前登录用户信息(/me需要用户上下文的令牌)
  • 控制器直接注入具体实现类GraphService,而非接口IGraphService,违反依赖倒置原则
  • 重复创建GraphServiceClient实例,代码冗余

分步解决方案

1. 安装必要的NuGet包

确保项目安装以下包:

Install-Package Microsoft.Graph
Install-Package Microsoft.Identity.Web
Install-Package Microsoft.Identity.Web.MicrosoftGraph

2. 修正Program.cs服务注册

在Program.cs中添加身份验证和Graph服务的配置,替换原有的AddScoped<IGraphService, GraphService>():

var builder = WebApplication.CreateBuilder(args);

// 添加Azure AD身份验证配置
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration)
    .EnableTokenAcquisitionToCallDownstreamApi(new[] { "User.Read" })
    .AddMicrosoftGraph(builder.Configuration.GetSection("Graph"))
    .AddInMemoryTokenCaches();

// 注册自定义Graph服务
builder.Services.AddScoped<IGraphService, GraphService>();

// MVC服务配置
builder.Services.AddControllersWithViews();

var app = builder.Build();

// 中间件配置
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

同时在appsettings.json中添加Graph配置节点:

"Graph": {
  "BaseUrl": "https://graph.microsoft.com/v1.0",
  "Scopes": "User.Read"
}

3. 修正GraphService实现

改用DI注入已配置好的GraphServiceClient,基于用户上下文令牌调用/me端点:

using Microsoft.Graph;
using Microsoft.Identity.Web;

namespace ClientMaster.Services.GraphService
{
    public class GraphService : IGraphService
    {
        private readonly GraphServiceClient _graphClient;

        public GraphService(GraphServiceClient graphClient)
        {
            _graphClient = graphClient;
        }

        public async Task<User> GetCurrentUser()
        {
            return await _graphClient.Me.Request()
                .Select(u => new {
                    u.DisplayName,
                    u.Mail,
                    u.UserPrincipalName
                })
                .GetAsync();
        }
    }
}

4. 修正IGraphService接口

更新方法名以明确语义:

using Microsoft.Graph;
using System.Threading.Tasks;

namespace ClientMaster.Services.GraphService
{
    public interface IGraphService
    {
        Task<User> GetCurrentUser();
    }
}

5. 修正HomeController注入逻辑

改为注入接口IGraphService,符合依赖注入最佳实践:

using ClientMaster.Models;
using ClientMaster.Services.GraphService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace ClientMaster.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IGraphService _graphService;

        public HomeController(ILogger<HomeController> logger, IGraphService graphService)
        {
            _logger = logger;
            _graphService = graphService;
        }

        public async Task<IActionResult> Index()
        {
            var user = await _graphService.GetCurrentUser();
            return View(user);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [AllowAnonymous]
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

关键说明

  • Microsoft.Identity.Web封装了令牌获取、缓存和Graph客户端配置,无需手动处理底层认证逻辑
  • /me端点仅支持用户上下文令牌,必须通过授权码流(用户登录后)获取,不能使用客户端凭证流
  • 确保Azure AD应用注册中已添加User.Read权限,并完成管理员授权

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:40:22