Use app.settings based on publish profile rather than ASPNETCORE_ENVIRONMENT

asked 2021-11-02T12:34:24.343+00:00
Luca Fongaro 96 Reputation points

I'm currently developing an application with core 3.1 and angular (client side). On my test server I need to publish two version of the same application (one for internal testing one for external testing), the change between the two versions are in the appsettings (two different databases and other detail). So I have two app.settings for staging environment.
Now, the problem: when I want to publish for one I need to replace the entire appsettings.Staging.json with one or another configuration (depends which I want to publish).

The only way I found to better manage this situation is to create a new configuration in the solution, associate it with the publish profile, slighty alter the program.cs file and override the Environment . My Program.cs file is:

public class Program
        public static void Main(string[] args)

        public static IHostBuilder CreateHostBuilder(string[] args) =>
                .ConfigureWebHostDefaults(webBuilder =>
        public static string Environment
                string environmentName;
                environmentName = "development";
#elif STAGING 
                environmentName = "staging";
                environmentName = "stagingDev";
                environmentName = "production";

                return environmentName;

staging and stagingDev are the two additional configuration I created.
There is a smarter way to manage this case?

A set of technologies in the .NET Framework for building web applications and XML web services.
2,524 questions
No comments
{count} votes

Accepted answer
  1. answered 2021-11-02T15:46:50.197+00:00
    Luca Fongaro 96 Reputation points

    Thanks for the reply,

    set with -p name=value on the dotnet publish command line.

    My bad, I forgot to write in the original post: I use Visual Studio enterprise 2019, I want visual studio 2019 to manage the process.
    However thanks to your reference to dotnet publish I found i can set an arbitrary value for the environment name directly in the publish profile and ignore the default of the server.

    For everyone like me use Visual Studio 2019 is possible to edit the *.pubxml file.
    Inside the element Propertygroup add an element called "EnvironmentName".

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" xmlns="">
            <!-- other property you normally found... -->
            <EnvironmentName>StagingDev</EnvironmentName> <----- this

    When you publish the application will read appsettings.StagingDev.json. Substitute StagingDev with whatever you want.


    No comments

1 additional answer

Sort by: Most helpful
  1. answered 2021-11-02T15:02:08.327+00:00
    Bruce ( 27,936 Reputation points

    Use environment variables like all the examples and set with -p name=value on the dotnet publish command line.

    No comments