且构网

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

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

更新时间:2022-11-06 17:55:52

如果其他人想知道如何在多个环境中使用不同的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 发布配置文件中(可以在属性-> PublishProfiles Studio的/ code>),默认情况下禁用所有内容文件

  • 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.