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

如何在新版Microsoft.Graph中添加Request Adapter?.NET C#适配指导

适配新版Microsoft Graph SDK添加Request Adapter(C#/.NET)

新版Microsoft Graph SDK(v5及以上)彻底重构了认证和请求适配逻辑,旧版的DelegateAuthenticationProvider已被移除,改用Azure Identity库的凭证类处理认证,同时GraphServiceClient的构造方式也发生了变化。以下是针对你旧代码的完整适配方案:

核心变化说明

  • 弃用旧版ConfidentialClientApplication,改用Azure.Identity.ClientSecretCredential管理服务主体认证
  • 无需手动实现Token注入逻辑,SDK通过BaseBearerTokenAuthenticationProvider自动处理
  • GraphServiceClient支持直接传入TokenCredential实例,内部自动构建RequestAdapter

完整适配代码

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;

private GraphServiceClient CreateGraphServiceClient()
{
    var scopes = new[] { "https://graph.microsoft.com/.default" };
    var tenantId = _configuration["Microsoft-Graph:tenantId"];
    var clientId = _configuration["Microsoft-Graph:clientId"];
    var clientSecret = _configuration["Microsoft-Graph:clientSecretValue"];

    // 初始化服务主体凭证,替代旧版的ConfidentialClientApplication
    var credential = new ClientSecretCredential(
        tenantId,
        clientId,
        clientSecret);

    // 直接传入凭证和作用域,SDK自动处理RequestAdapter和认证逻辑
    var graphClient = new GraphServiceClient(credential, scopes);

    return graphClient;
}

手动构建RequestAdapter的场景(自定义HttpClient等)

如果需要自定义HttpClient或精细控制RequestAdapter,可使用以下方式:

using Azure.Identity;
using Microsoft.Graph;
using System.Net.Http;

private GraphServiceClient CreateGraphServiceClientWithCustomAdapter()
{
    var scopes = new[] { "https://graph.microsoft.com/.default" };
    var tenantId = _configuration["Microsoft-Graph:tenantId"];
    var clientId = _configuration["Microsoft-Graph:clientId"];
    var clientSecret = _configuration["Microsoft-Graph:clientSecretValue"];

    var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    var httpClient = new HttpClient(); // 可自定义超时、代理等HttpClient配置

    // 构建认证提供者
    var authProvider = new BaseBearerTokenAuthenticationProvider(credential);

    // 创建RequestAdapter实例
    var requestAdapter = new HttpClientRequestAdapter(authProvider, httpClient: httpClient);
    requestAdapter.BaseUrl = "https://graph.microsoft.com/v1.0"; // 指定Graph API版本

    // 使用RequestAdapter初始化GraphServiceClient
    var graphClient = new GraphServiceClient(requestAdapter);

    return graphClient;
}

注意事项

  • 必须安装NuGet包:Microsoft.Graph(最新稳定版)和Azure.Identity,旧版Microsoft.Graph.Auth已被弃用,请勿使用
  • 修正你新版代码中的拼写错误:https://graph.micorsoft.com/.default → https://graph.microsoft.com/.default
  • 确保服务主体已获得对应的Graph API权限(且已完成管理员同意)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:21:03