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

如何正确构造IRequestAdapter解决Graph API非空异常问题

构造有效的IRequestAdapter实例解决空引用异常

你的代码中IRequestAdapter requestAdapter = null!;仅绕过了编译器非空检查,但运行时无实际实例,因此触发空引用异常。以下是正确构造IRequestAdapter的方法:

必要前提

确保已安装以下NuGet包:

  • Microsoft.Graph.Beta
  • Azure.Identity(用于身份验证)

构造步骤与代码示例

1. 客户端凭据流(适用于后台服务、无用户交互场景)

using Azure.Identity;
using Microsoft.Graph.Beta;

// 替换为你的Azure AD应用配置
var tenantId = "你的租户ID";
var clientId = "你的应用客户端ID";
var clientSecret = "你的应用客户端密钥";

// 创建身份验证凭据
var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

// 构造IRequestAdapter实例
var requestAdapter = new HttpClientRequestAdapter(credential);

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

// 调用API获取敏感度标签
var result = await graphClient.Users["user-dummy-email@stuff.com"].Security.InformationProtection.SensitivityLabels.GetAsync();

2. 交互式身份验证流(适用于有用户交互的桌面/Web应用)

若需以当前用户身份访问OneDrive文档,可使用交互式凭据:

using Azure.Identity;
using Microsoft.Graph.Beta;

// 替换为你的Azure AD应用配置
var tenantId = "你的租户ID";
var clientId = "你的应用客户端ID";
var redirectUri = new Uri("http://localhost"); // 需与应用注册中配置的重定向URI一致

// 创建交互式身份验证凭据
var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions
{
    TenantId = tenantId,
    ClientId = clientId,
    RedirectUri = redirectUri
});

// 构造IRequestAdapter实例
var requestAdapter = new HttpClientRequestAdapter(credential);

// 初始化GraphServiceClient并调用API
var graphClient = new GraphServiceClient(requestAdapter);
var result = await graphClient.Users["user-dummy-email@stuff.com"].Security.InformationProtection.SensitivityLabels.GetAsync();

说明

IRequestAdapter是Microsoft Graph SDK的核心接口,负责处理HTTP请求发送、身份验证、响应解析等逻辑。HttpClientRequestAdapter是该接口的实现类,必须传入有效的身份验证凭据(实现IAuthenticationProvider接口的实例,如Azure.Identity中的各类凭据类)才能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:27:16