Azure Function TimerTrigger集成Microsoft.Identity.Client遇程序集加载异常求助
问题场景
基于定时器触发的Azure Functions项目,配置如下:
- 语言:C#
- 目标框架:.NET 8.0
- 依赖包:Microsoft.Identity.Client(v4.74.1)、Microsoft.NET.Sdk.Functions(v4.6.0)
定时器触发函数代码:
[FunctionName("TimerTriggerFunc")] public static async Task Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log) { log.LogInformation($"Sync function {Version} started at: {DateTime.Now}"); var tokenInfo = await AuthAPIAccess.RetrieveAccessTokenFromGraphMSALAsync(log); }
在执行构建ConfidentialClientApplication的代码时,抛出异常:
var app = ConfidentialClientApplicationBuilder.Create(ClientID) .WithAuthority(AzureCloudInstance.AzurePublic, TenantID) .WithClientSecret(ClientSecret) .Build();
异常信息:
System.IO.FileNotFoundException
HResult=0x80070002
Message=Could not load file or assembly 'System.Security.Cryptography, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
Source=Microsoft.Identity.ClientStackTrace:
at Microsoft.Identity.Client.ConfidentialClientApplication..ctor(ApplicationConfiguration configuration)
at Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.Build()
at teMonitorStage.BusinessLogic.AuthAPIAccess.d__3.MoveNext() in
解决方案
1. 显式引入System.Security.Cryptography NuGet包
Azure Functions宿主环境默认未包含该组件的引用,需手动添加对应版本的依赖:
执行NuGet安装命令:
Install-Package System.Security.Cryptography -Version 8.0.0
或者直接在项目的.csproj文件中添加包引用:
<PackageReference Include="System.Security.Cryptography" Version="8.0.0" />
2. 确认项目运行时配置正确性
确保项目文件中目标框架和Functions版本配置正确:
<TargetFramework>net8.0</TargetFramework> <AzureFunctionsVersion>v4</AzureFunctionsVersion>
(当前使用的Microsoft.NET.Sdk.Functions v4.6.0已兼容.NET 8,无需调整版本)
3. 添加程序集绑定重定向(可选)
若存在版本冲突问题,在app.config或function.proj中添加绑定重定向规则,强制指向正确版本:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Security.Cryptography" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>
4. 清理并重建项目
清理缓存的旧依赖文件,重新构建项目:
- 删除项目目录下的
bin和obj文件夹 - 执行命令:
dotnet clean dotnet restore dotnet build
原因说明
MSAL v4.74.1依赖.NET 8版本的System.Security.Cryptography组件,但Azure Functions默认部署包中未包含该组件。显式添加依赖后,该程序集会被打包到部署包中,确保运行时能正确加载。
内容的提问来源于stack exchange,提问作者brendan davton

