且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 .Net 核心应用程序中发布特定于环境的应用程序设置?

更新时间:2022-11-06 18:27:01

如果其他人想知道如何为多个环境使用不同的 appsettings,这里是一个可能的解决方案.

If someone else is wondering how to use different appsettings for multiple environments here is a possible solution.

dotnet publish --configuration [Debug|Release] 将适当的 appsettings.json 文件复制到发布文件夹中,如果 *.csproj 对这些文件有条件逻辑:

dotnet publish --configuration [Debug|Release] will copy the appropriate appsettings.json file into the publish folder if *.csproj has a conditional logic for these files:

  • 首先在 .pubxml 发布配置文件(可以在 Visual Studio 的 Properties->PublishProfiles 中找到)禁用所有内容文件默认包含
  • First in the .pubxml publish profile file (can be found in Properties->PublishProfiles of Visual Studio) disable that all content files are included by default
<PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <EnableDefaultContentItems>false</EnableDefaultContentItems>
</PropertyGroup>

  • 然后指定条件调试/发布逻辑
<Choose>
    <When Condition="'$(Configuration)' == 'Debug'">
      <ItemGroup>
        <None Include="appsettings.json" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" />
        <None Include="appsettings.prod.json" CopyToOutputDirectory="Never" CopyToPublishDirectory="Never" />
      </ItemGroup>
    </When>
    <When Condition="'$(Configuration)' == 'Release'">
      <ItemGroup>
        <None Include="appsettings.json" CopyToOutputDirectory="Never" CopyToPublishDirectory="Never" />
        <None Include="appsettings.prod.json" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" />
      </ItemGroup>
    </When>
</Choose>

  • 最后在 Startup.cs 中尝试加载这两个文件
    • Finally inside Startup.cs try to load both files
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile($"appsettings.prod.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

我希望这个解决方案对您有所帮助.

I hope this solution, has been helpful.