【问题标题】:How to handle Appsettings for .net core 3.1 self contained single file publish如何处理 .net core 3.1 自包含单文件发布的 Appsettings
【发布时间】:2019-12-31 19:03:21
【问题描述】:

我有一个作为 Windows 服务托管的新 .NET Core 3.1 工作程序类。我正在使用模板创建的默认 appsettings.json 和 appsettings.environment.json。 在 ConfigureServices 期间从 hostContext 加载 appsettings

.ConfigureServices((hostContext, services) =>
   {
      services.AddHostedService<Worker>();
      services.Configure<BasicSettings>(hostContext.Configuration.GetSection("AppSettings"));
   });

我希望能够在部署后编辑 appsettings,以便在生产环境中更改设置。在我的机器上调试期间它可以正常工作。我更新了 csproj 文件以使用以下代码来尝试使 appsettings.json 不包含在单个文件中。

    <None Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
    </None>
    <None Include="appsettings.Development.json;appsettings.Production.json;">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
      <DependentUpon>appsettings.json</DependentUpon>
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
    </None>
  </ItemGroup>

添加后,发布过程确实创建了单个 exe 以及 3 个 appsettings.json 文件,但没有解决它。

当 Windows 服务启动时,它会将单个 exe 扩展至文件夹 C:\Users\ServiceLogonUser\AppData\Local\Temp.net\ServiceName\SomeRandomThing,其中包含发布时项目中存在的 appsettings.json。不是在 exe 旁边复制的 appsettings.json。如果我删除此文件夹,则会重新创建它,但会再次使用发布时存在的 appsettings.json。单个exe发布如何从同一文件夹中读取appsettings.json,以便发布后可以编辑文件?

【问题讨论】:

  • 你应该修改appsettings.Production.json,而不是appsettings.json不要删除该文件夹。 .exe 只是一个部署到该文件夹​​(如果它不存在)的包。
  • 唯一需要与.exe 一起部署的文件是appsettings.Production.jsonDevelopment 包含您的 开发 设置,不应发布
  • 问题是 exe 旁边的 appsettings.Production.json 没有被复制到 Temp 文件夹中。因此,我可以在生产中进行更改的唯一方法是编辑 temp 文件夹中的 json 文件。但是,如果我启动一个新版本,它会再次使用我发布时项目中存在的 json 文件创建一个新的临时文件夹 - 我每次都必须找到新的临时文件夹并手动编辑或复制 json发布一个版本。

标签: c# .net-core windows-services .net-core-3.0 .net-core-3.1


【解决方案1】:

我也遇到了同样的问题,通过项目文件中的这个简单更改解决了。

<None Include="appsettings.json">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  <CopyToPublishDirectory>Always</CopyToPublishDirectory>
  <ExcludeFromSingleFile>false</ExcludeFromSingleFile>
</None>
<None Include="appsettings.Development.json;appsettings.Production.json;">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  <CopyToPublishDirectory>Always</CopyToPublishDirectory>
  <DependentUpon>appsettings.json</DependentUpon>
  <ExcludeFromSingleFile>false</ExcludeFromSingleFile>
</None>

这会将 appsettings.json 和其他配置 JSON 文件捆绑到单个文件中,并在运行时解压到临时位置。

请参考here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 2020-04-08
  • 2021-05-24
  • 2019-05-01
  • 2017-09-06
相关资源
最近更新 更多