How to dynamically Change appsettings.json Based on Build Configuration in .NET

50 Views Asked by At

I'm working on a .NET application and I'm facing a challenge with managing different environments (e.g., development, staging, production). I want to dynamically modify my appsettings.json file based on the build configuration, so that each deployment environment uses its specific connection strings among other settings.

Currently, I have separate appsettings.json files (like appsettings.Development.json, appsettings.Staging.json, etc.), but I'm looking for a more streamlined approach to automatically select the right settings without manually changing them before each build/deployment.

I looked into using MSBuild conditions within the .csproj file to copy specific appsettings files based on the configuration, but it seems cumbersome and error-prone. I also considered environment variables, but I would prefer a solution that allows keeping all configurations within the project for simplicity.

Sometimes, during the build process (especially when not doing a full rebuild), it seems like the changes in the appsettings.json files do not get properly applied. For example, I could be deploying with the Production configuration, but the application still mistakenly uses settings from appsettings.Testing.json. This inconsistency is a significant concern, particularly when dealing with database connection strings. Since Im deploying directly with Gitlab CI/CD i need to ensure the build fully rebuilds and accepts the appsettings always

Iam using .net 6.0

0

There are 0 best solutions below