Azure Function App使用RestSharp遇System.Text.Json 7.0.0.0找不到错误
我试过针对「RestSharp: 无法加载文件或程序集'System.Text.Json, Version=7.0.0.0'」的解决方案,但没有效果。目前只想让代码在本地运行,已安装RestSharp 110.2.0和System.Text.Json 7.0.2,但仍出现以下错误:
FileNotFoundException: 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.
我的代码如下:
var options = new RestClientOptions("https://api.elliemae.com") { MaxTimeout = -1, }; var client = new RestClient(options); var request = new RestRequest("/oauth2/v1/token", Method.Post); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("grant_type", "password"); request.AddParameter("username", encompass.userName); request.AddParameter("password", encompass.password); request.AddParameter("client_id", encompass.apiClientId); request.AddParameter("client_secret", encompass.clientSecret); RestResponse response = client.Execute(request);
错误出现在实例化RestClient时。我的PackageReference配置如下:
<ItemGroup> <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" /> <PackageReference Include="RestSharp" Version="110.2.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.8.5" /> <PackageReference Include="System.Text.Json" Version="7.0.2" /> </ItemGroup>
错误依然存在,还有其他解决思路吗?我已经尝试了能找到的所有相关方案,上述代码使用RestSharp 106.12时可以正常获取访问令牌,但由于要部署到Azure,我希望使用最新版本的库。
添加程序集绑定重定向
在项目的app.config或web.config中添加绑定重定向配置,将对System.Text.Json 7.0.0.0版本的请求重定向到已安装的7.0.2版本:<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-7.0.2.0" newVersion="7.0.2.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>升级Azure Functions SDK版本
当前使用的Microsoft.NET.Sdk.Functions4.1.1可能自带了特定版本的System.Text.Json,与你安装的版本产生冲突。尝试将其升级到最新稳定版,再重新还原依赖,看是否能解决版本不匹配问题。清理项目缓存并重新生成
旧的编译缓存可能导致版本冲突,按以下步骤操作:- 删除项目根目录下的
bin和obj文件夹 - 执行命令
dotnet clean - 执行命令
dotnet restore - 重新生成项目
- 删除项目根目录下的
切换RestSharp的序列化器
RestSharp默认依赖System.Text.Json,可以手动切换为Newtonsoft.Json来绕开这个问题:- 安装NuGet包
RestSharp.Serializers.NewtonsoftJson - 修改实例化RestClient的代码:
var client = new RestClient(options).UseNewtonsoftJson();- 安装NuGet包
内容的提问来源于stack exchange,提问作者DanielGroff

