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

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.Functions 4.1.1可能自带了特定版本的System.Text.Json,与你安装的版本产生冲突。尝试将其升级到最新稳定版,再重新还原依赖,看是否能解决版本不匹配问题。

  • 清理项目缓存并重新生成
    旧的编译缓存可能导致版本冲突,按以下步骤操作:

    1. 删除项目根目录下的bin和obj文件夹
    2. 执行命令 dotnet clean
    3. 执行命令 dotnet restore
    4. 重新生成项目
  • 切换RestSharp的序列化器
    RestSharp默认依赖System.Text.Json,可以手动切换为Newtonsoft.Json来绕开这个问题:

    1. 安装NuGet包RestSharp.Serializers.NewtonsoftJson
    2. 修改实例化RestClient的代码:
    var client = new RestClient(options).UseNewtonsoftJson();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:15:19