Discovered a three-step build in Visual Studio approach for publishing environment-specific appsetting files (Windows, PowerShell).
- appsettings.json
- appsettings.Development.json
- appsettings.Staging.json
- appsettings.Production.json
This approach will publish
- appsettings.json and
- appsettings.$(ASPNETCORE_ENVIRONMENT).json.
Step 1. Update csproj:
<!-- App Settings -->
<ItemGroup>
<Content Remove="appsettings.json" />
<Content Remove="appsettings.*.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json" CopyToOutputDirectory="Always" />
<Content Include="appsettings.$(ASPNETCORE_ENVIRONMENT).json" DependentUpon="appsettings.json" CopyToOutputDirectory="Always" />
</ItemGroup>
Step 2. Set an environment variable in PowerShell:
# Read
[Environment]::GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "User")
# Output: empty string if not set or 'Staging' in my case
# Set environment variable "User" or "Machine" level
[Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Staging", "User")
Step 3. Then close and reopen Visual Studio solution to enable Visual Studio to see the environment variable and reload project structure accordingly.
- Now appsettings.json is a parent and appsettings.Staging.json is a nested file.
- If you set another environment (for example "Production") and then close and Visual Studio and reopen your solution, then you will appsettings.json as a parent and appsettings.Production.json as a nested file.

Final step. Run publishing.

Note: publishing profile environment variables do not affect publishing configuration. This approach uses PowerShell to set an environment variable and enables environment-specific publishing. Please see link for more details on environment variables.
