更新时间: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
中找到)禁用所有内容文件默认包含.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
中尝试加载这两个文件
Startup.cs
try to load both filespublic 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.