通过 Nuget 安装时,.Net 核心解决方案中的 Nuget 内容文件未被复制

Nuget Content Files in .Net core solution not getting copied when installing through Nuget

我无法在使用 nuget 包资源管理器创建 nuget 包时添加的 .Net 核心 Web 应用程序项目中复制内容静态文件。同样的事情在 .Net 框架项目模板中被正确复制,但在 .net 核心模板中却没有。我正在使用 VS 2015 更新 3.Am 我在这里遗漏了什么?任何帮助将不胜感激。

下面是我的内容文件结构快照。

关于这个有一个nuget blog post,只是目前不支持。

Supported Project Types

This feature is only for packages that will be installed to projects that are managed using a project.json file. Currently only two projects types are managed by a project.json.

  • UWP apps
  • Portable class libraries

The contentFiles option is not available for other project types.

.net Core 项目中排除了这个基本功能,真是可惜。特别是因为支持 PCL,它是 .net Core 项目的子集。

GitHub 上有很多关于此的问题,目前还不清楚此功能是否会很快恢复。

阅读这篇文章后 post 我想出了一个变通办法。我创建了一个 .Net 程序集项目并完全清空了它的所有内容。然后我将该项目移动到与 .Net Core Web 应用程序项目相同的目录中。我没有从 Web 应用程序添加 NuGet 包引用,而是从 .Net 程序集项目添加它。所有文件都正确复制到目录中,并自动添加到 Web 项目中,因为它们共享同一目录。这个解决方案感觉很脏,但它允许我使用 .Net Core Web 项目的 NuGet 包管理静态文件。

一些 public nuget 包(例如 https://www.nuget.org/packages/NUnit3TestAdapter/3.10.0 or https://www.nuget.org/packages/Selenium.WebDriver.ChromeDriver/) can copy files. I've tried to investigate it (https://github.com/nunit/nunit3-vs-adapter and https://github.com/jsakamoto/nupkg-selenium-webdriver-chromedriver)。但看起来,他们已经实施了非常棘手的解决方法

好像还是不支持。 “破解”它的唯一方法是使用 MSBuild 目标和构建事件。

根据 this 文档:

build
MSBuild .targets and .props files Automatically inserted into the project file or project.lock.json (NuGet 3.x+).

所以要让它与任何文件一起工作,例如:“config.xml”作为 Nuget 静态内容:

  1. 创建您的 XY.nuspec 文件(像往常一样)
  2. 将 config.xml 包含到 Nuget 中:<file src="config.xml" target="contentFiles\any\any\config.xml" />
  3. 添加一个新的 .targets 文件 XY.targets
  4. 将新的 XY.targets 文件包含到您的包中的“build”文件夹中。 <file src="XY.targets" target="build"/>

XY.targets 文件的内容

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <ContentFilesPath>$(MSBuildThisFileDirectory)..\contentFiles\any\any\</ContentFilesPath>
  </PropertyGroup>
  <Target Name="CopyConfigs" BeforeTargets="PreBuildEvent">
    <Copy SourceFiles="$(ContentFilesPath)\config.xml" DestinationFiles="$(ProjectDir)config.xml" SkipUnchangedFiles="true" Condition="!Exists('$(ProjectDir)config.xml')"></Copy>
  </Target>
</Project>

打包并安装 Nuget 后,此 MSBuild 目标将成为缓存包的一部分,并且将 运行 在每个构建中(当前在构建之前)。

此解决方案的问题:

  • 添加的文件在您构建解决方案之前仍然链接。在构建阶段 (BeforeTargets="") 文件被复制。直到这个文件仍然只是链接!!!
  • 如果您将内容文件设置为具有生成操作并复制到项目的输出目录,这些设置将会丢失!

不幸的是,这是目前最好的解决方案。