使用 MSBuild 在 Server 2016 上构建针对 .Net 4.0 的 ASP.Net 项目

Use MSBuild to build ASP.Net project targeting .Net 4.0 on Server 2016

我在 Windows Server 2016 上设置了 Jenkins 构建服务器。我安装了 'Build Tools for Visual Studio 2017'(最新版本的 MSBuild)。当我尝试构建一个针对 .Net 4.0 的项目时,我收到此错误消息:

C:\Program Files (x86)\Microsoft Visual Studio17\BuildTools\MSBuild.0\Bin\Microsoft.Common.CurrentVersion.targets(1122,5): error MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.0" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.

于是查看'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0',果然这个文件夹里没有dll,只有xml个文件。

所以我尝试安装完整的 .Net 4.0 框架,以为会安装参考程序集,但我收到这些消息:

1) Microsoft .NET Framework 4 is already a part of this operating system. You do not need to install the .NET Framework 4 redistributable.

2) Same or higher version of .NET Framework 4 has already been installed on this computer.

所以我 Google 到处找了几个网站说 '.NET Framework 4.5.2 is considered to be an "in-place update" to the .NET 4 family, with no need to recompile applications' 我想也许我可以只安装 .Net 4.5.2 目标包并使用这个参数和 MSBuild 来定位它们:

/property:FrameworkPathOverride="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2"

果然,这似乎有效。问题是我不完全理解参考程序集和目标包等等。我担心,虽然看起来我可能已经解决了问题,但稍后我会发现,在更远的道路上,我引入了其他一些讨厌的问题。

问题

更新

我没有提到我还尝试通过 this link 安装 .Net Framework 4.0.3 milti-targeting 包,但我收到以下错误:

Microsoft .NET Framework 4 Multi-Targeting Pack was not found. Please repair your installation for Microsoft Visual Studio 2010 in order to get this update.

简答

我不建议您继续使用 FrameworkPathOverride。这会将您的应用程序更改为像 .NET 4.5.2 而不是 4.0 一样进行编译。会有意想不到的后果。

您可以在此处下载 .NET Framework 4.0 目标包:https://www.microsoft.com/en-us/download/details.aspx?id=29052

或者,您可以通过在 "Individual Components" 中选择 Visual Studio 2017 安装程序来下载 .NET 4.0 目标包。

更多详情

The problem is I don't fully understand reference assemblies and targeting packs and whatnot.

"Reference assemblies" 基本上类似于.NET 中的头文件。当您为 .NET Framework 4.0 编译应用程序时,您 "targeting" .NET 4.0 中可用的 API 运行 时间。这构成了您的应用程序可以 运行 的最低 运行 时间版本。但是,该应用程序将在计算机上安装的 .NET Framework 运行time 版本上执行(它是全局共享版本),几乎肯定会比 4.0 更新。

安装目标包只是意味着您正在将 'header files' 的副本安装到您​​的机器上。您的计算机仍将安装 .NET Framework 4.5.x 或 4.6 运行time。

由于 .NET 4.0 不受支持并且大多数机器将拥有 4.5.2 或更新版本,您应该考虑改为针对 .NET Framework 4.5.2 进行编译。您可以从 Visual Studio 中的项目属性页面执行此操作。或者,您可以编辑 csproj 文件。

如果您使用 "classic",更详细的 csproj 格式,将像这样

   <PropertyGroup>
      <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
   </PropertyGroup>

如果您使用的是 "new",用于 VS 2017 的更苗条的 csproj,那将是

   <PropertyGroup>
      <TargetFramework>net452</TargetFramework>
   </PropertyGroup>