C# TFS Api 从另一个程序集调用时抛出异常?

C# TFS Api throws exception when called from another assembly?

我有一个 minimal working exmaple on github 来重现我的案例。以下代码抛出异常:

        var wc = new WindowsCredential(new NetworkCredential(userName, password, domain));
        var credentials = new VssCredentials(wc);
        var buildHttpClient = new Microsoft.TeamFoundation.Build.WebApi.BuildHttpClient(new Uri(tfsUrl), credentials);

异常如下(我为德语消息道歉,意思是“找不到文件或依赖项”):

System.IO.FileNotFoundException
HResult=0x80070002
Message=Die Datei oder Assembly "System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" oder eine Abhängigkeit davon wurde nicht gefunden. Das System kann die angegebene Datei nicht finden.
Source=Microsoft.VisualStudio.Services.WebApi

仅当从另一个程序集(例如我的 ConsoleExample 或 TestExample)调用代码时才会抛出此异常。该代码在它所在的程序集中工作正常。您插入的凭据似乎并不重要。看来您甚至不需要 运行 TFS 服务器。

感谢任何帮助。我可以用 Visual Studio 2019 和 2017 在两台计算机上重现它。注意:该代码适用于相应 NuGet 包的旧版本。

用样本测试,我可以重现这个问题。此问题的根本原因可能是 ConsoleExample 项目缺少依赖项或引用。

程序集名称:Newtonsoft.Json System.Net.Http.Formatting System.IdentityModel.Tokens.Jwt

您需要在 ConsoleExample 项目中添加依赖程序集或程序集引用。

这里有两种方法可以解决这个问题:

方法一:在ConsoleExample -> App.config.

中添加依赖程序集

App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.7.1.0" newVersion="6.7.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

方法 2:您可以通过 Add-> References -> Browser

手动添加对 ConsoleExample Project 的引用

由于 BuildClientExample 项目可以 运行 成功,您可以在本地计算机上找到这些程序集

更新:

单元测试示例

我 运行 单元测试示例并得到同样的问题。

Could not load file or assembly 'System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, ...

要解决此问题,您可以将 app.config 文件添加到示例中,同时手动 add the target References。

然后您需要将相同的 dependentAssembly 添加到 app.config 文件中。

并且您需要确保这两种方法引用的程序集是相同的版本。