如何将 appsettings.json 复制到 DEBUG 文件夹,作为 dotnet build 的一部分

How to copy appsettings.json to DEBUG folder, as part of dotnet build

我有一个控制台应用程序,它使用 appsettings.json 来保存配置值。

在 Visual Studio IDE 中,当我为 appsettings.json 设置 AlwaysCopy 时,它将被复制到 DEBUG 文件夹,作为构建。

但是,在 .net 核心中,当我 运行 dotnet build 时,它不会将 appsettings.json 复制到 DEBUG 文件夹。 我已经将以下 xml 配置添加到 .csproj

  <Content Include="appsettings.json">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  </Content>

当我执行 dotnet publish 时,它正在被复制到发布文件夹。但是,当我 dotnet build 时,它并没有发生。你能告诉我,为什么它没有发生吗?我应该怎么做才能将 appsettings.json 复制到 DEBUG 文件夹?

在另一个线程中找到答案是 Whosebug(The difference between build and publish in VS?)。与 .NET Framework 相比,.NET Core 中的构建和发布是不同的。

Building .NET Framework applications will generate the same files as Publish. It will create all the dependencies as binaries including external dependencies(NuGets for instance). So the product of dotnet build is ready to be transferred to another machine to run

Building .NET Core applications, if the project has third-party dependencies, such as libraries from NuGet, they're resolved from the NuGet cache and aren't available with the project's built output. Therefore the product of dotnet build isn't ready to be transferred to another machine to run. You need to run Publish to get all 3rd party dependencies as binaries in output folder.

如果我们想让文件成为发布的一部分,我们需要添加以下属性。在构建中,此文件不会复制到 DEBUG/RELEASE 文件夹。

<Content Include="appsettings.json">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  </Content>