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

使用GraphServiceClient读取M365邮件时遇DelegateAuthenticationProvider等报错求助

问题解决方法

报错原因

你的代码基于Microsoft Graph SDK v4及更早版本编写,但当前使用的是v5+版本,API存在重大变更,导致两个报错:

  1. DelegateAuthenticationProvider 在v5版本中已被移除
  2. Request() 方法在v5版本中已被简化,无需显式调用

修复后的代码

首先确保安装最新的Microsoft Graph NuGet包:

Install-Package Microsoft.Graph

修改后的代码如下:

using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Net.Http.Headers;
using Microsoft.Identity.Client;
// 新增命名空间,用于BearerTokenAuthenticationProvider
using Microsoft.Graph.Authentication;

namespace GraphTest.Helpers
{
    public class GraphHelper
    {
        public static async Task<CachedUser> GetUserDetailsAsync(string accessToken)
        {
            // 替换旧认证方式为BearerTokenAuthenticationProvider
            var authProvider = new BearerTokenAuthenticationProvider(accessToken);
            var graphClient = new GraphServiceClient(authProvider);

            // 移除Request()方法,直接调用Me属性后链式操作
            var user = await graphClient.Me
                .Select(u => new
                {
                    u.DisplayName,
                    u.Mail,
                    u.UserPrincipalName
                })
                .GetAsync();

            return new CachedUser
            {
                Avatar = string.Empty,
                DisplayName = user.DisplayName,
                Email = string.IsNullOrEmpty(user.Mail) ?
                    user.UserPrincipalName : user.Mail
            };
        }
    }
}

关键变更说明

  • 认证方式替换:使用BearerTokenAuthenticationProvider(来自Microsoft.Graph.Authentication命名空间)替代旧的DelegateAuthenticationProvider,直接传入access token即可完成Bearer认证
  • 简化请求写法:v5 SDK中,graphClient.Me直接返回请求构建器,无需调用Request()方法,可直接链式调用Select、GetAsync等方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:43:14