Azure Functions发布后缺失System.Text.Json的问题求助
问题重现
近期合并了Azure Functions服务项目与公共库项目,为解决合规性和兼容性问题升级了部分依赖项,已将所有项目目标框架更新为.NET 6,使用Azure Functions V4版本。函数应用部署正常,但调用时触发以下错误:
Exception while executing function: ActiveTestEventGenV2 Could not load file or assembly 'System.Text.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.
已尝试以下方法但均无效:
- 添加
RestoreProjectStyle配置 - 在各项目csproj中显式添加System.Text.Json依赖
- 在Directory.Build.targets中配置全局显式依赖
- 通过构建脚本将DLL复制到发布目录(DLL已存在但问题依旧)
- 设置
Copy Local为true - 使用Visual Studio合并依赖工具(未检测到多版本冲突)
解决思路与操作步骤
一、先做依赖版本精准分析
1. 用dotnet命令排查依赖链
在解决方案根目录执行以下命令,列出所有直接/间接依赖的System.Text.Json版本,定位是否有依赖强制引入了7.0.0.0:
dotnet list package --include-transitive | findstr System.Text.Json
2. 用dotnet-dsrouter做深度依赖分析
安装工具:
dotnet tool install -g dotnet-dsrouter
生成详细依赖树JSON文件:
dotnet dsrouter dump --output dependencies.json
打开文件可精准定位哪个项目/第三方库拉取了7.0.0.0版本的System.Text.Json。
3. 明确Azure Functions运行时的默认依赖
Azure Functions V4(.NET 6)运行时自带的是System.Text.Json 6.x版本,若代码或依赖试图加载7.x版本,运行时环境本身没有该版本程序集,即便手动复制DLL也可能因加载策略问题无法识别。
二、针对性解决方法
1. 全局统一System.Text.Json版本为6.x
在解决方案根目录新建/修改Directory.Build.props,强制所有项目(包括传递依赖)使用指定的6.x版本:
<Project> <PropertyGroup> <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> </PropertyGroup> <ItemGroup> <PackageVersion Include="System.Text.Json" Version="6.0.7" /> </ItemGroup> </Project>
2. 配置程序集绑定重定向
若无法避免引入7.0.0.0版本,在函数项目的host.json中添加重定向配置(Azure Functions V4的重定向配置与普通.NET项目不同):
{ "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[3.*, 4.0.0)" }, "runtimeOptions": { "assemblyBinding": { "dependencies": [ { "assembly": "System.Text.Json", "publicKeyToken": "cc7b13ffcd2ddd51", "bindingRedirects": [ { "oldVersion": "0.0.0.0-7.0.0.0", "newVersion": "6.0.0.0" } ] } ] } } }
此配置会让运行时将对7.0.0.0的请求重定向到自带的6.x版本。
3. 检查公共库的依赖与目标框架
- 若公共库为自研,确认其目标框架也是.NET 6,且未引用System.Text.Json 7.x版本;
- 若公共库是第三方NuGet包,检查其依赖项是否包含7.x版本的System.Text.Json,考虑降级包版本或联系作者更新兼容.NET 6的版本。
4. 清理残留文件后重新部署
执行以下步骤避免旧文件冲突:
# 本地清理 dotnet clean # 重新构建 dotnet build --configuration Release # 重新发布 dotnet publish --configuration Release --output ./publish
之后删除Azure函数应用的旧文件,再上传新的发布包。
问题原理说明
本质是程序集版本不匹配:
- .NET 6的Azure Functions V4运行时自带System.Text.Json 6.x版本,代码或传递依赖请求的7.x版本不在运行时环境中,导致找不到;
- 手动复制7.x DLL到发布目录后,Azure Functions运行时可能优先使用自带版本,或因加载路径/权限问题无法识别手动添加的文件;
- 传递依赖冲突是核心诱因:某个第三方库或公共库依赖了System.Text.Json 7.x,未做全局版本统一时,构建阶段会引入该版本,但运行时无法提供支持。
内容的提问来源于stack exchange,提问作者metamemelord

