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

使用Graph API获取所有用户时Azure Function遇System.Text.Encoding.Web错误

问题解决:.NET Core 3.1 Azure Function调用Graph API用户列表报System.Text.Encoding.Web版本错误

问题背景

在.NET Core 3.1环境下,Azure Function中调用graphClient.Users.Request().GetAsync()获取用户列表时,触发System.Text.Encoding.Web版本6.0.0.0相关错误,但调用graphClient.Users[Id].Request().GetAsync()获取单个用户正常,且相同代码在MVC应用和.NET6环境的Function中可正常运行。使用的依赖版本:Graph API 4.5.0、Microsoft.NET.sdk.Functions 3.1.1。

解决方案

1. 显式锁定兼容的System.Text.Encoding.Web版本

在Azure Function项目的.csproj文件中添加对System.Text.Encoding.Web的显式引用,指定兼容.NET Core 3.1的版本(推荐4.7.2),避免依赖自动升级到6.0版本:

<PackageReference Include="System.Text.Encoding.Web" Version="4.7.2" />

2. 检查并清理依赖冲突

通过NuGet包管理器查看项目依赖树,确认所有Graph SDK相关依赖未间接引入.NET6专属的包版本。如果发现有依赖自动升级到6.0系列,手动指定兼容.NET Core 3.1的版本。

3. 自定义HttpClient实例初始化GraphServiceClient

避免使用默认的HttpClient配置,手动创建HttpClient实例来初始化GraphServiceClient,减少宿主环境的配置干扰:

// 初始化代码调整
var httpClient = new HttpClient();
graphClient = new GraphServiceClient(httpClient, new DelegateAuthenticationProvider(async (requestMessage) => {
    var authResult = await _clientApplication
        .AcquireTokenForClient(scopes)
        .ExecuteAsync();
    requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}));

4. 确认Function运行时配置

在host.json中明确指定运行时版本为~3,确保Azure Function运行在.NET Core 3.1的宿主环境:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.*, 4.0.0)"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:01:27