.NET 8环境连接Microsoft Dynamics 365 CRM遇System.ServiceModel缺失错误
我正尝试使用个人API客户端密钥对Microsoft Dynamics 365 CRM进行身份验证,但在通过连接字符串创建CrmServiceClient类实例时,遇到以下错误:
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified
当前使用.NET 8,项目依赖如下:
<PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="8.0.8" /> <PackageReference Include="Microsoft.CrmSdk.CoreAssemblies" Version="9.0.2.56" /> <PackageReference Include="Microsoft.CrmSdk.XrmTooling.CoreAssembly" Version="9.1.1.65" /> <PackageReference Include="Microsoft.Windows.Compatibility" Version="8.0.8" /> <PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" /> <PackageReference Include="System.ServiceModel.Http" Version="8.0.0" /> <PackageReference Include="System.ServiceModel.NetTcp" Version="8.0.0" /> <PackageReference Include="System.ServiceModel.Primitives" Version="8.0.0" /> <PackageReference Include="System.ServiceModel.Security" Version="6.0.0" /> <PackageReference Include="Xero.NetStandard.OAuth2" Version="9.1.0" /> <PackageReference Include="Xero.NetStandard.OAuth2Client" Version="1.6.0" />
解决方法
统一System.ServiceModel包版本
当前依赖中System.ServiceModel.Security为6.0.0版本,其他相关包是8.0.0,版本不一致会引发程序集绑定冲突。将System.ServiceModel.Security升级到8.0.0版本:<PackageReference Include="System.ServiceModel.Security" Version="8.0.0" />添加程序集绑定重定向
在项目的app.config或web.config中加入绑定重定向配置,让.NET 8自动将旧版本System.ServiceModel的引用指向新版本:<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.ServiceModel" publicKeyToken="b77a5c561934e089" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="8.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>检查SDK包兼容性
确认Microsoft.CrmSdk.XrmTooling.CoreAssembly(9.1.1.65)是否完全支持.NET 8,若问题仍存在,可尝试升级到最新兼容版本的Dynamics 365 SDK包。清理重建项目
删除项目的bin和obj文件夹,执行dotnet clean和dotnet restore命令,再重新编译项目,确保依赖正确加载。
内容的提问来源于stack exchange,提问作者furqan majeed

