本文主要介绍当创建测试项目或将应用程序和测试升级到ASP.NET Core 2.1/.NET Core 2.1,运行测试失败,程序集加载异常。 System.IO.FileNotFoundException : Could not load file or assembly 'Microsoft.AspNetCore, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.

1、异常信息

运行测试失败,程序集加载异常如下

System.IO.FileNotFoundException : Could not load file or assembly 'Microsoft.AspNetCore, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.

当添加对其他库的引用时,还会有构建时警告信息如下

warning MSB3277: Found conflicts between different versions of "Microsoft.Extensions.Options" that could not be resolved.
warning MSB3277: Found conflicts between different versions of "Microsoft.Extensions.Configuration.Abstractions" that could not be resolved.
warning MSB3277: Found conflicts between different versions of "Microsoft.AspNetCore.Hosting.Abstractions" that could not be resolved.
warning MSB3277: Found conflicts between different versions of "Microsoft.Extensions.DependencyInjection.Abstractions" that could not be resolved.
warning MSB3277: Found conflicts between different versions of "Microsoft.AspNetCore.Http.Abstractions" that could not be resolved.
warning MSB3277: Found conflicts between different versions of "Microsoft.AspNetCore.Http.Features" that could not be resolved.

2、解决方案

ASP.NET Core 2.1使用一个新的“共享框架”来运行ASP.NET Core 应用程序。测试项目需要修改/更新,以使用以下方法之一使用这个共享框架:

1)在项目文件(.csproj)的第一行中更改测试项目的<Project>标记,以使用Web SDK(Microsoft.NET.Sdk.Web而不是Microsoft.NET.Sdk)并将包引用添加到Microsoft.AspNetCore.App(或.All,如果您 在没有指定版本的情况下,在Web项目中使用它,测试项目的项目文件(.csproj)如下:

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<!-- other references to xunit, test SDK etc. -->
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AspNetCoreAppToTest\AspNetCoreAppToTest.csproj" />
</ItemGroup>
</Project>

2)备选方案

保持Sdk不变,并向共享框架包中添加一个PackageReference,但要指定一个版本。这可以通过简单地向Microsoft.AspNetCore.App添加一个NuGet引用来实现。但是,这可能会导致问题,因为SDK可能会选择在ASP.NET Core的新补丁发布时,更新引用.NET Core发布,工具也更新了。需要为每个补丁版本更新NuGet引用。


推荐文档